Example #1
0
        public MediaEntry GetMediaEntry(ISceneChildEntity part, int face)
        {
            MediaEntry me = null;

            CheckFaceParam(part, face);

            List<MediaEntry> media = part.Shape.Media;

            if (null == media)
            {
                me = null;
            }
            else
            {
                lock (media)
                    me = media[face];

                // TODO: Really need a proper copy constructor down in libopenmetaverse
                if (me != null)
                    me = MediaEntry.FromOSD(me.GetOSD());
            }

//            MainConsole.Instance.DebugFormat("[MOAP]: GetMediaEntry for {0} face {1} found {2}", part.Name, face, me);

            return me;
        }
Example #2
0
 public void Initialize (IScriptModulePlugin ScriptEngine, ISceneChildEntity host, uint localID, UUID itemID, ScriptProtectionModule module)
 {
     m_itemID = itemID;
     m_ScriptEngine = ScriptEngine;
     m_host = host;
     ScriptProtection = module;
 }
        /// <summary>
        ///     Take the serialized string and set up the Components for this object
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="serialized"></param>
        public void DeserializeComponents(ISceneChildEntity obj, string serialized)
        {
            //Pull the OSDMap out for components
            OSDMap map;
            try
            {
                if (serialized == "")
                    map = new OSDMap();
                else
                    map = (OSDMap) OSDParser.DeserializeJson(serialized);
            }
            catch
            {
                //Bad JSON? Just return
                return;
            }

            //Now check against the list of components we have loaded
            foreach (KeyValuePair<string, OSD> kvp in map)
            {
                PropertyInfo property = obj.GetType().GetProperty(kvp.Key);
                if (property != null)
                {
                    property.SetValue(obj, Util.OSDToObject(kvp.Value, property.PropertyType), null);
                }
            }
            map.Clear();
            map = null;
        }
Example #4
0
 public void Initialize (IScriptModulePlugin ScriptEngine, ISceneChildEntity host, uint localID, UUID itemID, ScriptProtectionModule module)
 {
     m_itemID = itemID;
     m_ScriptEngine = ScriptEngine;
     m_host = host;
     ScriptProtection = module;
     AssetConnector = Aurora.DataManager.DataManager.RequestPlugin<IAssetConnector>();
 }
 public void DeleteFrom(ISceneChildEntity Part, UUID ItemID)
 {
     lock (StateSaveLock)
     {
         //if we did remove something, resave it
         if (Part.StateSaves.Remove(ItemID))
             Part.ParentEntity.HasGroupChanged = true;
     }
 }
Example #6
0
        public void Initialize (IScriptModulePlugin ScriptEngine, ISceneChildEntity host, uint localID, UUID itemID, ScriptProtectionModule module)
        {
            m_ScriptEngine = ScriptEngine;
            m_host = host;
            m_localID = localID;
            m_itemID = itemID;
            ScriptProtection = module;

            m_comms = World.RequestModuleInterface<IScriptModuleComms>();
        }
 public void Deserialization (ISceneChildEntity obj, XmlTextReader reader)
 {
     string components = reader.ReadElementContentAsString ("Components", string.Empty);
     if (components != "") {
         try {
             DeserializeComponents (obj, components);
         } catch (Exception ex) {
             MainConsole.Instance.Warn ("[Component manager]: Error on deserializing Components! " + ex);
         }
     }
 }
        public void PlaybackState (ISceneChildEntity part)
        {
            if (part != null)
            {
                part.Undoing = true;

                bool ChangedScale = false;
                bool ChangedPos = false;

                if (part.UUID == part.ParentEntity.UUID)
                {
                    if (Position != Vector3.Zero)
                    {
                        ChangedPos = true;
                        part.ParentEntity.AbsolutePosition = Position;
                    }

                    part.SetRotationOffset (true, Rotation, true);
                    if (Scale != Vector3.Zero)
                    {
                        ChangedScale = true;
                        part.Scale = Scale;
                    }

                    foreach (
                        ISceneChildEntity child in
                            part.ParentEntity.ChildrenEntities ().Where (child => child.UUID != part.UUID)) {
                        child.Undo (); //No updates here, child undo will do it on their own
                    }
                } else {
                    if (Position != Vector3.Zero)
                    {
                        ChangedPos = true;
                        part.FixOffsetPosition (Position, false);
                    }

                    part.UpdateRotation (Rotation);
                    if (Scale != Vector3.Zero)
                    {
                        ChangedScale = true;
                        part.Resize (Scale);
                    }
                }

                part.Undoing = false;
                var updateFlags =
                    (ChangedScale ? PrimUpdateFlags.Shape : PrimUpdateFlags.None) |
                    (ChangedPos ? PrimUpdateFlags.Position : PrimUpdateFlags.None) |
                    PrimUpdateFlags.Rotation;

                part.ScheduleUpdate (updateFlags);
            }
        }
Example #9
0
 public UndoState (ISceneChildEntity part)
 {
     if (part != null) {
         if (part.UUID == part.ParentEntity.UUID) {
             Position = part.ParentEntity.AbsolutePosition;
             Rotation = part.GetRotationOffset ();
             Scale = part.Shape.Scale;
         } else {
             Position = part.OffsetPosition;
             Rotation = part.GetRotationOffset ();
             Scale = part.Shape.Scale;
         }
     }
 }
Example #10
0
        //internal IWindLightSettingsModule m_lightShareModule;

        public void Initialize(IScriptModulePlugin ScriptEngine, ISceneChildEntity host, uint localID, UUID itemID, ScriptProtectionModule module)
        {
            m_ScriptEngine = ScriptEngine;
            m_host = host;
            m_localID = localID;
            m_itemID = itemID;
            ScriptProtection = module;

            if (m_ScriptEngine.Config.GetBoolean("AllowLightShareFunctions", false))
                m_LSFunctionsEnabled = true;

            m_comms = World.RequestModuleInterface<IScriptModuleComms>();
            if (m_comms == null)
                m_LSFunctionsEnabled = false;
        }
Example #11
0
        public void Initialize(IScriptModulePlugin ScriptEngine, ISceneChildEntity host, uint localID, UUID itemID, ScriptProtectionModule module)
        {
            m_ScriptEngine = ScriptEngine;
            m_host = host;
            m_localID = localID;
            m_itemID = itemID;

            if (m_ScriptEngine.Config.GetBoolean("AllowOSFunctions", false))
                m_OSFunctionsEnabled = true;

            m_ScriptDelayFactor =
                    m_ScriptEngine.Config.GetFloat("ScriptDelayFactor", 1.0f);
            m_ScriptDistanceFactor =
                    m_ScriptEngine.Config.GetFloat("ScriptDistanceLimitFactor", 1.0f);
            ScriptProtection = module;
        }
Example #12
0
 public bool Compare (ISceneChildEntity part)
 {
     if (part != null) {
         if (part.UUID == part.ParentEntity.UUID) {
             if (Position == part.AbsolutePosition && Rotation == part.GetRotationOffset () &&
                 Scale == part.Shape.Scale)
                 return true;
             return false;
         }
         if (Position == part.OffsetPosition && Rotation == part.GetRotationOffset () &&
             Scale == part.Shape.Scale)
             return true;
         return false;
     }
     return false;
 }
Example #13
0
        /// <summary>
        /// Copy a task (prim) inventory item to another task (prim)
        /// </summary>
        /// <param name="destId"></param>
        /// <param name="part"></param>
        /// <param name="itemId"></param>
        public void MoveTaskInventoryItemToObject (UUID destId, ISceneChildEntity part, UUID itemId)
        {
            TaskInventoryItem srcTaskItem = part.Inventory.GetInventoryItem(itemId);

            if (srcTaskItem == null)
            {
                MainConsole.Instance.ErrorFormat(
                    "[PRIM INVENTORY]: Tried to retrieve item ID {0} from prim {1}, {2} for moving"
                        + " but the item does not exist in this inventory",
                    itemId, part.Name, part.UUID);

                return;
            }

            ISceneChildEntity destPart = m_scene.GetSceneObjectPart (destId);

            if (destPart == null)
            {
                MainConsole.Instance.ErrorFormat(
                        "[PRIM INVENTORY]: " +
                        "Could not find prim for ID {0}",
                        destId);
                return;
            }

            // Can't transfer this
            //
            if ((part.OwnerID != destPart.OwnerID) && ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0))
                return;

            if (part.OwnerID != destPart.OwnerID && (destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
            {
                // object cannot copy items to an object owned by a different owner
                // unless llAllowInventoryDrop has been called

                return;
            }

            // must have both move and modify permission to put an item in an object
            if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0)
            {
                return;
            }

            TaskInventoryItem destTaskItem = new TaskInventoryItem
                                                 {
                                                     ItemID = UUID.Random(),
                                                     CreatorID = srcTaskItem.CreatorID,
                                                     CreatorData = srcTaskItem.CreatorData,
                                                     AssetID = srcTaskItem.AssetID,
                                                     GroupID = destPart.GroupID,
                                                     OwnerID = destPart.OwnerID,
                                                     ParentID = destPart.UUID,
                                                     ParentPartID = destPart.UUID,
                                                     BasePermissions = srcTaskItem.BasePermissions,
                                                     EveryonePermissions = srcTaskItem.EveryonePermissions,
                                                     GroupPermissions = srcTaskItem.GroupPermissions,
                                                     CurrentPermissions = srcTaskItem.CurrentPermissions,
                                                     NextPermissions = srcTaskItem.NextPermissions,
                                                     Flags = srcTaskItem.Flags,
                                                     SalePrice = srcTaskItem.SalePrice,
                                                     SaleType = srcTaskItem.SaleType
                                                 };



            if (destPart.OwnerID != part.OwnerID)
            {
                if (m_scene.Permissions.PropagatePermissions())
                {
                    destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions &
                            (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
                    destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions &
                            (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
                    destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions &
                            (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
                    destTaskItem.BasePermissions = srcTaskItem.BasePermissions &
                            (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
                    destTaskItem.CurrentPermissions |= 16; // Slam!
                }
            }

            destTaskItem.Description = srcTaskItem.Description;
            destTaskItem.Name = srcTaskItem.Name;
            destTaskItem.InvType = srcTaskItem.InvType;
            destTaskItem.Type = srcTaskItem.Type;

            destPart.Inventory.AddInventoryItem(destTaskItem, part.OwnerID != destPart.OwnerID);

            if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
                part.Inventory.RemoveInventoryItem(itemId);

            IScenePresence avatar;

            if (m_scene.TryGetScenePresence(srcTaskItem.OwnerID, out avatar))
                destPart.GetProperties(avatar.ControllingClient);
        }
Example #14
0
        public bool DistanceCulling(IScenePresence client, IEntity entity, IScene scene)
        {
            float DD = client.DrawDistance;

            if (DD < 32) //Limit to a small distance
            {
                DD = 32;
            }
            if (DD > scene.RegionInfo.RegionSizeX &&
                DD > scene.RegionInfo.RegionSizeY)
            {
                return(true); //Its larger than the region, no culling check even necessary
            }
            Vector3 posToCheckFrom = client.GetAbsolutePosition();

            if (client.IsChildAgent)
            {
                /*if (m_cachedXOffset == 0 && m_cachedYOffset == 0) //Not found yet
                 * {
                 *  int RegionLocX, RegionLocY;
                 *  Util.UlongToInts(client.RootAgentHandle, out RegionLocX, out RegionLocY);
                 *  m_cachedXOffset = scene.RegionInfo.RegionLocX - RegionLocX;
                 *  m_cachedYOffset = scene.RegionInfo.RegionLocY - RegionLocY;
                 * }
                 * //We need to add the offset so that we can check from the right place in child regions
                 * if (m_cachedXOffset < 0)
                 *  posToCheckFrom.X = scene.RegionInfo.RegionSizeX -
                 *                     (scene.RegionInfo.RegionSizeX + client.AbsolutePosition.X + m_cachedXOffset);
                 * if (m_cachedYOffset < 0)
                 *  posToCheckFrom.Y = scene.RegionInfo.RegionSizeY -
                 *                     (scene.RegionInfo.RegionSizeY + client.AbsolutePosition.Y + m_cachedYOffset);
                 * if (m_cachedXOffset > scene.RegionInfo.RegionSizeX)
                 *  posToCheckFrom.X = scene.RegionInfo.RegionSizeX -
                 *                     (scene.RegionInfo.RegionSizeX - (client.AbsolutePosition.X + m_cachedXOffset));
                 * if (m_cachedYOffset > scene.RegionInfo.RegionSizeY)
                 *  posToCheckFrom.Y = scene.RegionInfo.RegionSizeY -
                 *                     (scene.RegionInfo.RegionSizeY - (client.AbsolutePosition.Y + m_cachedYOffset));*/
            }
            Vector3 entityPosToCheckFrom = Vector3.Zero;
            bool    doHeavyCulling       = false;

            if (entity is ISceneEntity)
            {
                doHeavyCulling = true;
                //We need to check whether this object is an attachment, and if so, set it so that we check from the avatar's
                // position, rather than from the offset of the attachment
                ISceneEntity sEntity = (ISceneEntity)entity;
                if (sEntity.RootChild.IsAttachment)
                {
                    IScenePresence attachedAvatar = scene.GetScenePresence(sEntity.RootChild.AttachedAvatar);
                    if (attachedAvatar != null)
                    {
                        entityPosToCheckFrom = attachedAvatar.AbsolutePosition;
                    }
                }
                else
                {
                    entityPosToCheckFrom = sEntity.RootChild.GetGroupPosition();
                }
            }
            else if (entity is IScenePresence)
            {
                //We need to check whether this presence is sitting on anything, so that we can check from the object's
                // position, rather than the offset position of the object that the avatar is sitting on
                IScenePresence pEntity = (IScenePresence)entity;
                if (pEntity.Sitting)
                {
                    ISceneChildEntity sittingEntity = scene.GetSceneObjectPart(pEntity.SittingOnUUID);
                    if (sittingEntity != null)
                    {
                        entityPosToCheckFrom = sittingEntity.GetGroupPosition();
                    }
                }
                else
                {
                    entityPosToCheckFrom = pEntity.GetAbsolutePosition();
                }
            }
            //If the distance is greater than the clients draw distance, its out of range
            if (Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom) >
                DD * DD) //Use squares to make it faster than having to do the sqrt
            {
                if (!doHeavyCulling)
                {
                    return(false); //Don't do the hardcore checks
                }
                ISceneEntity childEntity = (entity as ISceneEntity);
                if (childEntity != null && HardCullingCheck(childEntity))
                {
                    #region Side culling check (X, Y, Z) plane checks

                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom + new Vector3(childEntity.OOBsize.X, 0, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom - new Vector3(childEntity.OOBsize.X, 0, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom + new Vector3(0, childEntity.OOBsize.Y, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom - new Vector3(0, childEntity.OOBsize.Y, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom + new Vector3(0, 0, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom - new Vector3(0, 0, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }

                    #endregion

                    #region Corner checks ((x,y),(-x,-y),(x,-y),(-x,y), (y,z),(-y,-z),(y,-z),(-y,z), (x,z),(-x,-z),(x,-z),(-x,z))

                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom +
                                                new Vector3(childEntity.OOBsize.X, childEntity.OOBsize.Y, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom -
                                                new Vector3(childEntity.OOBsize.X, childEntity.OOBsize.Y, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom +
                                                new Vector3(childEntity.OOBsize.X, -childEntity.OOBsize.Y, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom -
                                                new Vector3(childEntity.OOBsize.X, -childEntity.OOBsize.Y, 0)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom +
                                                new Vector3(0, childEntity.OOBsize.Y, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom -
                                                new Vector3(0, childEntity.OOBsize.Y, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom +
                                                new Vector3(0, childEntity.OOBsize.Y, -childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom -
                                                new Vector3(0, childEntity.OOBsize.Y, -childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom +
                                                new Vector3(childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom -
                                                new Vector3(childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom +
                                                new Vector3(-childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }
                    if (
                        Vector3.DistanceSquared(posToCheckFrom,
                                                entityPosToCheckFrom -
                                                new Vector3(-childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) <
                        DD * DD) //Use squares to make it faster than having to do the sqrt
                    {
                        return(true);
                    }

                    #endregion
                }
                return(false);
            }

            return(true);
        }
        private byte[] CopyInventoryFromNotecard(Stream request, UUID agentID)
        {
            OSDMap rm              = (OSDMap)OSDParser.DeserializeLLSDXml(HttpServerHandlerHelpers.ReadFully(request));
            UUID   FolderID        = rm["folder-id"].AsUUID();
            UUID   ItemID          = rm["item-id"].AsUUID();
            UUID   NotecardID      = rm["notecard-id"].AsUUID();
            UUID   ObjectID        = rm["object-id"].AsUUID();
            UUID   notecardAssetID = UUID.Zero;

            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                    {
                        notecardAssetID = item.AssetID;
                    }
                }
            }
            else
            {
                notecardAssetID = m_scene.InventoryService.GetItemAssetID(agentID, NotecardID);
            }
            if (notecardAssetID != UUID.Zero)
            {
                byte[] asset = m_scene.AssetService.GetData(notecardAssetID.ToString());
                if (asset != null)
                {
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset);
                    noteCardAsset.Decode();
                    bool found       = false;
                    UUID lastOwnerID = UUID.Zero;
                    foreach (
                        InventoryItem notecardObjectItem in
                        noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found       = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
                    if (found)
                    {
                        m_scene.InventoryService.GiveInventoryItemAsync(agentID, lastOwnerID, ItemID, FolderID, false,
                                                                        (item) =>
                        {
                            IClientAPI client;
                            m_scene.ClientManager.TryGetValue(
                                agentID, out client);
                            if (item != null)
                            {
                                client.SendBulkUpdateInventory(item);
                            }
                            else
                            {
                                client.SendAlertMessage(
                                    "Failed to retrieve item");
                            }
                        });
                    }
                }
            }

            return(new byte[0]);
        }
Example #16
0
        public void changed (ISceneChildEntity part, uint change)
        {
            ScriptData[] datas = ScriptEngine.ScriptProtection.GetScripts(part.UUID);

            if (datas == null || datas.Length == 0)
            {
                datas = ScriptEngine.ScriptProtection.GetScripts(part.ParentEntity.RootChild.UUID);
                if (datas == null || datas.Length == 0)
                    return;
            }
            string functionName = "changed";
            object[] param = new Object[] { new LSL_Types.LSLInteger(change) };

            foreach (ScriptData ID in datas)
            {
                if (CheckIfEventShouldFire(ID, functionName, param))
                    m_scriptEngine.AddToScriptQueue(ID, functionName, new DetectParams[0], EventPriority.FirstStart, param);
            }
        }
Example #17
0
        public void control (ISceneChildEntity part, UUID itemID, UUID agentID, uint held, uint change)
        {
            if(part == null)
                return;
            ScriptData ID = ScriptEngine.ScriptProtection.GetScript(part.UUID, itemID);

            if (ID == null)
                return;

            string functionName = "control";
            object[] param = new object[] {
                    new LSL_Types.LSLString(agentID.ToString()),
                    new LSL_Types.LSLInteger(held),
                    new LSL_Types.LSLInteger(change)};

            if (CheckIfEventShouldFire(ID, functionName, param))
                m_scriptEngine.AddToScriptQueue(ID, functionName, new DetectParams[0], EventPriority.FirstStart, param);
        }
Example #18
0
        /// <summary>
        ///     SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="scene">Can be null</param>
        public void SendEmail(UUID objectID, string address, string subject, string body, IScene scene)
        {
            //Check if address is empty
            if (address == string.Empty)
            {
                return;
            }

            /*
             * //FIXED:Check the email is correct form in REGEX
             * //const string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
             * //                                  + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
             * //                                  + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
             * //                                  + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
             * //                                  + @"[a-zA-Z]{2,}))$";
             */
            //Regex EMailreStrict = new Regex(EMailpatternStrict);
            //bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            bool isEMailStrictMatch = Utilities.IsValidEmail(address);

            if (!isEMailStrictMatch)
            {
                MainConsole.Instance.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > m_MaxEmailSize)
            {
                MainConsole.Instance.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
                return;
            }

            string LastObjectName       = string.Empty;
            string LastObjectPosition   = string.Empty;
            string LastObjectRegionName = string.Empty;

            if (scene != null)
            {
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition,
                                              out LastObjectRegionName, scene);
            }

            if (!address.EndsWith(m_InterObjectHostname))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // regular email, send it out
                    Thread threadSendMail;
                    threadSendMail = new Thread(delegate()
                    {
                        try
                        {
                            //Creation EmailMessage

                            string fromEmailAddress;

                            if (scene != null && objectID != UUID.Zero)
                            {
                                fromEmailAddress = objectID + "@" + m_HostName;
                            }
                            else
                            {
                                fromEmailAddress = "no-reply@" + m_HostName;
                            }

                            var fromAddress = new MailAddress(fromEmailAddress);
                            var toAddress   = new MailAddress(address);

                            if (scene != null)
                            {
                                // If Object Null Don't Include Object Info Headers (Offline IMs)
                                if (objectID != UUID.Zero)
                                {
                                    body = body + "\nObject-Name: " + LastObjectName +
                                           "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                           LastObjectPosition + "\n\n";
                                }
                            }

                            //Config SMTP Server
                            var smtpServer                   = new SmtpClient();
                            smtpServer.Host                  = SMTP_SERVER_HOSTNAME;
                            smtpServer.Port                  = SMTP_SERVER_PORT;
                            smtpServer.EnableSsl             = SMTP_SERVER_PORT == 587 ? true: false;
                            smtpServer.DeliveryMethod        = SmtpDeliveryMethod.Network;
                            smtpServer.UseDefaultCredentials = false;
                            smtpServer.Credentials           = new NetworkCredential(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                            smtpServer.Timeout               = 15000;

                            // Beware !! This effectively ignores the ssl validation and assumes that all is correct
                            // For Mono, requires importation of the Google smtpd certificate (see SMTPEmail.ini.example)
                            // Possibly not needed for Windows
                            //ServicePointManager.ServerCertificateValidationCallback =
                            //    delegate(object sim, X509Certificate certificate, X509Chain chain SslPolicyErrors sslPolicyErrors)
                            //{ return true; };

                            // if ((!SMTP_SERVER_MONO_CERT) && (Utilities.IsLinuxOs))
                            ServicePointManager.ServerCertificateValidationCallback = delegate {
                                return(true);
                            };

                            // create the message
                            var emailMessage     = new MailMessage(fromAddress, toAddress);
                            emailMessage.Subject = subject;
                            emailMessage.Body    = body;

                            // sample for adding attachments is needed sometime :)
                            //if File(Exist(fullFileName))
                            //{
                            //    var mailAttactment = new Attachment(fullFileName);
                            //    emailMessage.Attachments.Add(mailAttactment);
                            //}

                            // send the message
                            try
                            {
                                smtpServer.Send(emailMessage);
                            } catch (SmtpException ex)
                            {
                                SmtpStatusCode status = ex.StatusCode;
                                if (status == SmtpStatusCode.Ok)
                                {
                                    MainConsole.Instance.Info("[EMAIL] EMail sent to: " + address + " from object: " +
                                                              fromEmailAddress);
                                }
                                else
                                {
                                    MainConsole.Instance.Info("[EMAIL] EMail error sending to: " + address + " from object: " +
                                                              fromEmailAddress + " status: " + ex.Message);
                                }
                            }
                        } catch (Exception e)
                        {
                            MainConsole.Instance.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                            didError = true;
                        }
                    });

                    threadSendMail.IsBackground = true;
                    threadSendMail.Start();
                }
                if (((didError) || (m_localOnly)) && (scene != null))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName, scene);
                    if (part != null)
                    {
                        IScenePresence sp = scene.GetScenePresence(part.OwnerID);
                        if ((sp != null) && (!sp.IsChildAgent))
                        {
                            sp.ControllingClient.SendAlertMessage(
                                "llEmail: email module not configured for outgoing emails");
                        }
                    }
                }
            }
            else
            {
                // inter object email, keep it in the family
                string guid = address.Substring(0, address.IndexOf("@", StringComparison.Ordinal));
                UUID   toID = new UUID(guid);

                if (IsLocal(toID, scene))
                {
                    // object in this region
                    InsertEmail(toID, new Email
                    {
                        time =
                            ((int)
                             ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds))
                            .
                            ToString(CultureInfo.InvariantCulture),
                        subject = subject,
                        sender  = objectID.ToString() + "@" + m_InterObjectHostname,
                        message = "Object-Name: " + LastObjectName +
                                  "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                  LastObjectPosition + "\n\n" + body,
                        toPrimID = toID
                    });
                }
                else
                {
                    // object on another region

                    Email email = new Email
                    {
                        time =
                            ((int)
                             ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                            ToString(CultureInfo.InvariantCulture),
                        subject  = subject,
                        sender   = objectID.ToString() + "@" + m_InterObjectHostname,
                        message  = body,
                        toPrimID = toID
                    };
                    IEmailConnector conn = Framework.Utilities.DataManager.RequestPlugin <IEmailConnector>();
                    conn.InsertEmail(email);
                }
            }
        }
Example #19
0
 public void TriggerControlEvent (ISceneChildEntity part, UUID scriptUUID, UUID avatarID, uint held, uint _changed)
 {
     ScriptControlEvent handlerScriptControlEvent = OnScriptControlEvent;
     if (handlerScriptControlEvent != null)
     {
         foreach (ScriptControlEvent d in handlerScriptControlEvent.GetInvocationList ())
         {
             try
             {
                 d (part, scriptUUID, avatarID, held, _changed);
             }
             catch (Exception e)
             {
                 m_log.ErrorFormat (
                     "[EVENT MANAGER]: Delegate for TriggerControlEvent failed - continuing.  {0} {1}",
                     e.ToString (), e.StackTrace);
             }
         }
     }
 }
Example #20
0
 public SOPObjectMaterial(int m_face, ISceneChildEntity m_parent)
 {
     this.m_face   = m_face;
     this.m_parent = m_parent;
 }
Example #21
0
        /// <summary>
        ///   This method is called by the LLUDPServer and should never be called by anyone else
        ///   It loops through the available updates and sends them out (no waiting)
        /// </summary>
        /// <param name = "numUpdates">The number of updates to send</param>
        public void SendPrimUpdates(int numPrimUpdates, int numAvaUpdates)
        {
            if (m_numberOfLoops < NUMBER_OF_LOOPS_TO_WAIT)
            //Wait for the client to finish connecting fully before sending out bunches of updates
            {
                m_numberOfLoops++;
                return;
            }

            if (m_inUse || m_presence.IsInTransit)
            {
                return;
            }

            m_inUse = true;
            //This is for stats
            int AgentMS = Util.EnvironmentTickCount();

            #region New client entering the Scene, requires all objects in the Scene

            ///If we havn't started processing this client yet, we need to send them ALL the prims that we have in this Scene (and deal with culling as well...)
            if (!m_SentInitialObjects && m_presence.DrawDistance != 0.0f)
            {
                SendInitialObjects();
            }

            int presenceNumToSend       = numAvaUpdates;
            List <EntityUpdate> updates = new List <EntityUpdate>();
            lock (m_presenceUpdatesToSendLock)
            {
                //Send the numUpdates of them if that many
                // if we don't have that many, we send as many as possible, then switch to objects
                if (m_presenceUpdatesToSend.Count != 0)
                {
                    try
                    {
#if UseDictionaryForEntityUpdates
                        Dictionary <uint, EntityUpdate> .Enumerator e = m_presenceUpdatesToSend.GetEnumerator();
                        e.MoveNext();
                        List <uint> entitiesToRemove = new List <uint>();
#endif
                        int count = m_presenceUpdatesToSend.Count > presenceNumToSend
                                        ? presenceNumToSend
                                        : m_presenceUpdatesToSend.Count;
                        for (int i = 0; i < count; i++)
                        {
#if UseRemovingEntityUpdates
                            EntityUpdate update = ((EntityUpdate)m_presenceUpdatesToSend[0]);

                            /*if (m_EntitiesInPacketQueue.Contains (update.Entity.UUID))
                             * {
                             *  m_presenceUpdatesToSend.RemoveAt (0);
                             *  m_presenceUpdatesToSend.Insert (m_presenceUpdatesToSend.Count, update.Entity.UUID, update);
                             *  continue;
                             * }
                             * m_EntitiesInPacketQueue.Add (update.Entity.UUID);*/
                            m_presenceUpdatesToSend.RemoveAt(0);
                            if (update.Flags == PrimUpdateFlags.ForcedFullUpdate)
                            {
                                SendFullUpdateForPresence((IScenePresence)update.Entity);
                            }
                            else
                            {
                                updates.Add(update);
                            }
#elif UseDictionaryForEntityUpdates
                            EntityUpdate update = e.Current.Value;
                            entitiesToRemove.Add(update.Entity.LocalId); //Remove it later
                            if (update.Flags == PrimUpdateFlags.ForcedFullUpdate)
                            {
                                SendFullUpdateForPresence((IScenePresence)update.Entity);
                            }
                            else
                            {
                                updates.Add(update);
                            }
                            e.MoveNext();
#else
                            EntityUpdate update = m_presenceUpdatesToSend.Dequeue();
                            if (update.Flags == PrimUpdateFlags.ForcedFullUpdate)
                            {
                                SendFullUpdateForPresence((IScenePresence)update.Entity);
                            }
                            else
                            {
                                updates.Add(update);
                            }
#endif
                        }
#if UseDictionaryForEntityUpdates
                        foreach (uint id in entitiesToRemove)
                        {
                            m_presenceUpdatesToSend.Remove(id);
                        }
#endif
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.WarnFormat("[SceneViewer]: Exception while running presence loop: {0}", ex);
                    }
                }
            }
            if (updates.Count != 0)
            {
                presenceNumToSend -= updates.Count;
                m_presence.ControllingClient.SendAvatarUpdate(updates);
            }
            updates.Clear();

            List <AnimationGroup> animationsToSend = new List <AnimationGroup>();
            lock (m_presenceAnimationsToSendLock)
            {
                //Send the numUpdates of them if that many
                // if we don't have that many, we send as many as possible, then switch to objects
                if (m_presenceAnimationsToSend.Count != 0 && presenceNumToSend > 0)
                {
                    try
                    {
                        int count = m_presenceAnimationsToSend.Count > presenceNumToSend
                                        ? presenceNumToSend
                                        : m_presenceAnimationsToSend.Count;
                        for (int i = 0; i < count; i++)
                        {
                            AnimationGroup update = m_presenceAnimationsToSend.Dequeue();

                            /*if (m_AnimationsInPacketQueue.Contains (update.AvatarID))
                             * {
                             *  m_presenceAnimationsToSend.RemoveAt (0);
                             *  m_presenceAnimationsToSend.Insert (m_presenceAnimationsToSend.Count, update.AvatarID, update);
                             *  continue;
                             * }
                             * m_AnimationsInPacketQueue.Add (update.AvatarID);*/
                            animationsToSend.Add(update);
                        }
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.WarnFormat("[SceneViewer]: Exception while running presence loop: {0}", ex);
                    }
                }
            }
            foreach (AnimationGroup update in animationsToSend)
            {
                m_presence.ControllingClient.SendAnimations(update);
            }
            animationsToSend.Clear();

            int primsNumToSend = numPrimUpdates;

            List <IEntity> entities = new List <IEntity>();
            lock (m_objectPropertiesToSendLock)
            {
                //Send the numUpdates of them if that many
                // if we don't have that many, we send as many as possible, then switch to objects
                if (m_objectPropertiesToSend.Count != 0)
                {
                    try
                    {
                        int count = m_objectPropertiesToSend.Count > primsNumToSend
                                        ? primsNumToSend
                                        : m_objectPropertiesToSend.Count;
                        for (int i = 0; i < count; i++)
                        {
                            ISceneChildEntity entity = ((ISceneChildEntity)m_objectPropertiesToSend[0]);

                            /*if (m_PropertiesInPacketQueue.Contains (entity.UUID))
                             * {
                             *  m_objectPropertiesToSend.RemoveAt (0);
                             *  m_objectPropertiesToSend.Insert (m_objectPropertiesToSend.Count, entity.UUID, entity);
                             *  continue;
                             * }
                             * m_PropertiesInPacketQueue.Add (entity.UUID);*/
                            m_objectPropertiesToSend.RemoveAt(0);
                            entities.Add(entity);
                        }
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.WarnFormat("[SceneViewer]: Exception while running presence loop: {0}", ex);
                    }
                }
            }
            if (entities.Count > 0)
            {
                primsNumToSend -= entities.Count;
                m_presence.ControllingClient.SendObjectPropertiesReply(entities);
            }

            updates = new List <EntityUpdate>();
            lock (m_objectUpdatesToSendLock)
            {
                if (m_objectUpdatesToSend.Count != 0)
                {
                    try
                    {
                        int count = m_objectUpdatesToSend.Count > primsNumToSend
                                        ? primsNumToSend
                                        : m_objectUpdatesToSend.Count;
                        for (int i = 0; i < count; i++)
                        {
                            EntityUpdate update = ((EntityUpdate)m_objectUpdatesToSend[0]);

                            /*if (m_EntitiesInPacketQueue.Contains (update.Entity.UUID))
                             * {
                             *  m_objectUpdatesToSend.RemoveAt (0);
                             *  m_objectUpdatesToSend.Insert (m_objectUpdatesToSend.Count, update.Entity.UUID, update);
                             *  continue;
                             * }
                             * m_EntitiesInPacketQueue.Add (update.Entity.UUID);*/

                            //Fix the CRC for this update
                            //Increment the CRC code so that the client won't be sent a cached update for this
                            if (update.Flags != PrimUpdateFlags.PrimFlags)
                            {
                                ((ISceneChildEntity)update.Entity).CRC++;
                            }

                            updates.Add(update);
                            m_objectUpdatesToSend.RemoveAt(0);
                        }
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.WarnFormat("[SceneViewer]: Exception while running object loop: {0}", ex);
                    }
                    m_presence.ControllingClient.SendPrimUpdate(updates);
                }
            }


            //Add the time to the stats tracker
            IAgentUpdateMonitor reporter =
                (IAgentUpdateMonitor)
                m_presence.Scene.RequestModuleInterface <IMonitorModule>().GetMonitor(
                    m_presence.Scene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.AgentUpdateCount);
            if (reporter != null)
            {
                reporter.AddAgentTime(Util.EnvironmentTickCountSubtract(AgentMS));
            }

            m_inUse = false;
        }
Example #22
0
        public bool BuyObject(IClientAPI remoteClient, UUID categoryID, uint localID, byte saleType)
        {
            ISceneChildEntity part = m_scene.GetSceneObjectPart(localID);

            if (part == null)
            {
                return(false);
            }

            if (part.ParentEntity == null)
            {
                return(false);
            }

            ISceneEntity       group           = part.ParentEntity;
            ILLClientInventory inventoryModule = m_scene.RequestModuleInterface <ILLClientInventory>();

            switch (saleType)
            {
            case 1:     // Sell as original (in-place sale)
                uint effectivePerms = group.GetEffectivePermissions();

                if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
                    }
                    return(false);
                }

                group.SetOwnerId(remoteClient.AgentId);
                group.SetRootPartOwner(part, remoteClient.AgentId, remoteClient.ActiveGroupId);

                if (m_scene.Permissions.PropagatePermissions())
                {
                    foreach (ISceneChildEntity child in group.ChildrenEntities())
                    {
                        child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
                        child.TriggerScriptChangedEvent(Changed.OWNER);
                        child.ApplyNextOwnerPermissions();
                    }
                }

                part.ObjectSaleType = 0;
                part.SalePrice      = 10;

                group.HasGroupChanged = true;
                part.GetProperties(remoteClient);
                part.TriggerScriptChangedEvent(Changed.OWNER);
                group.ResumeScripts();
                part.ScheduleUpdate(PrimUpdateFlags.ForcedFullUpdate);

                break;

            case 2:     // Sell a copy
                Vector3 inventoryStoredPosition = new Vector3
                                                      (((group.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeX)
                              ? m_scene.RegionInfo.RegionSizeX - 1
                              : group.AbsolutePosition.X)
                                                      ,
                                                      (group.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeY)
                             ? m_scene.RegionInfo.RegionSizeY - 1
                             : group.AbsolutePosition.X,
                                                      group.AbsolutePosition.Z);

                Vector3 originalPosition = group.AbsolutePosition;

                group.AbsolutePosition = inventoryStoredPosition;

                string sceneObjectXml = SceneEntitySerializer.SceneObjectSerializer.ToOriginalXmlFormat(group);
                group.AbsolutePosition = originalPosition;

                uint perms = group.GetEffectivePermissions();

                if ((perms & (uint)PermissionMask.Transfer) == 0)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
                    }
                    return(false);
                }

                AssetBase asset = new AssetBase(UUID.Random(), part.Name,
                                                AssetType.Object, group.OwnerID)
                {
                    Description = part.Description, Data = Utils.StringToBytes(sceneObjectXml)
                };
                asset.ID = m_scene.AssetService.Store(asset);

                InventoryItemBase item = new InventoryItemBase
                {
                    CreatorId   = part.CreatorID.ToString(),
                    CreatorData = part.CreatorData,
                    ID          = UUID.Random(),
                    Owner       = remoteClient.AgentId,
                    AssetID     = asset.ID,
                    Description = asset.Description,
                    Name        = asset.Name,
                    AssetType   = asset.Type,
                    InvType     = (int)InventoryType.Object,
                    Folder      = categoryID
                };


                uint nextPerms = (perms & 7) << 13;
                if ((nextPerms & (uint)PermissionMask.Copy) == 0)
                {
                    perms &= ~(uint)PermissionMask.Copy;
                }
                if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
                {
                    perms &= ~(uint)PermissionMask.Transfer;
                }
                if ((nextPerms & (uint)PermissionMask.Modify) == 0)
                {
                    perms &= ~(uint)PermissionMask.Modify;
                }

                item.BasePermissions     = perms & part.NextOwnerMask;
                item.CurrentPermissions  = perms & part.NextOwnerMask;
                item.NextPermissions     = part.NextOwnerMask;
                item.EveryOnePermissions = part.EveryoneMask &
                                           part.NextOwnerMask;
                item.GroupPermissions = part.GroupMask &
                                        part.NextOwnerMask;
                item.CurrentPermissions |= 16;     // Slam!
                item.CreationDate        = Util.UnixTimeSinceEpoch();

                m_scene.InventoryService.AddItemAsync(item,
                                                      (itm) => remoteClient.SendInventoryItemCreateUpdate(itm, 0));
                break;

            case 3:     // Sell contents
                List <UUID> invList = part.Inventory.GetInventoryList();

                bool okToSell =
                    invList.Select(invID => part.Inventory.GetInventoryItem(invID))
                    .All(item1 => (item1.CurrentPermissions & (uint)PermissionMask.Transfer) != 0);

                if (!okToSell)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(
                            remoteClient, "This item's inventory doesn't appear to be for sale");
                    }
                    return(false);
                }

                if (invList.Count > 0)
                {
                    if (inventoryModule != null)
                    {
                        inventoryModule.MoveTaskInventoryItemsToUserInventory(remoteClient.AgentId, part.Name, part,
                                                                              invList);
                    }
                }
                break;
            }

            return(true);
        }
Example #23
0
        private static int getNumberOfSides(ISceneChildEntity 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);
        }
Example #24
0
        public double GetUpdatePriority(IScenePresence client, IEntity entity)
        {
            double priority = 0;

            if (entity == null)
            {
                return(double.PositiveInfinity);
            }

            bool adjustRootPriority = true;

            try
            {
                /*switch (UpdatePrioritizationScheme)
                 * {
                 *  case UpdatePrioritizationSchemes.Time:
                 *      priority = GetPriorityByTime();
                 *      break;
                 *  case UpdatePrioritizationSchemes.Distance:
                 *      priority = GetPriorityByDistance(client, entity);
                 *      break;
                 *  case UpdatePrioritizationSchemes.SimpleAngularDistance:
                 *      priority = GetPriorityByDistance(client, entity); //This (afaik) always has been the same in OpenSim as just distance (it is in 0.6.9 anyway)
                 *      break;
                 *  case UpdatePrioritizationSchemes.FrontBack:
                 *      priority = GetPriorityByFrontBack(client, entity);
                 *      break;
                 *  case UpdatePrioritizationSchemes.BestAvatarResponsiveness:
                 *      priority = GetPriorityByBestAvatarResponsiveness(client, entity);
                 *      break;
                 *  case UpdatePrioritizationSchemes.OOB:*/
                adjustRootPriority = false; //It doesn't need it
                priority           = GetPriorityByOOBDistance(client, entity);

                /*break;
                 *  default:
                 *      throw new InvalidOperationException("UpdatePrioritizationScheme not defined.");
                 * }*/
            }
            catch (Exception ex)
            {
                if (!(ex is InvalidOperationException))
                {
                    MainConsole.Instance.Warn("[PRIORITY]: Error in finding priority of a prim/user:" + ex);
                }
                //Set it to max if it errors
                priority = double.PositiveInfinity;
            }

            // Adjust priority so that root prims are sent to the viewer first.  This is especially important for
            // attachments acting as huds, since current viewers fail to display hud child prims if their updates
            // arrive before the root one.

            if (adjustRootPriority && entity is ISceneChildEntity)
            {
                ISceneChildEntity sop = ((ISceneChildEntity)entity);
                if (sop.IsRoot)
                {
                    ISceneEntity grp = sop.ParentEntity;
                    priority -= (grp.BSphereRadiusSQ + 0.5f);
                }


                if (sop.IsRoot)
                {
                    if (priority >= double.MinValue + 0.05)
                    {
                        priority -= 0.05;
                    }
                }
                else
                {
                    if (priority <= double.MaxValue - 0.05)
                    {
                        priority += 0.05;
                    }
                }
            }

            return(priority);
        }
Example #25
0
        /// <summary>
        /// Move the given items from the object task inventory to the agent's inventory
        /// </summary>
        /// <param name="destID"></param>
        /// <param name="name"></param>
        /// <param name="host"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public UUID MoveTaskInventoryItemsToUserInventory (UUID destID, string name, ISceneChildEntity host, List<UUID> items)
        {
            //InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(destID);

            UUID newFolderID = UUID.Random();

           // InventoryFolderBase newFolder = new InventoryFolderBase(newFolderID, name, destID, -1, rootFolder.ID, rootFolder.Version);
           // m_scene.InventoryService.AddFolder(newFolder);

            //int countLeft = items.Count;
            //foreach (UUID itemID in items)
            Util.FireAndForget((o) => 
            {
                //InventoryItemBase agentItem = CreateAgentInventoryItemFromTask(destID, host, itemID);
             InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(destID);
               InventoryFolderBase newFolder = new InventoryFolderBase(newFolderID, name, destID, -1, rootFolder.ID, rootFolder.Version); 
               m_scene.InventoryService.AddFolder(newFolder);

                //if (agentItem != null)
                foreach (UUID itemID in items)

                {
                    //agentItem.Folder = newFolderID;
                 InventoryItemBase agentItem = CreateAgentInventoryItemFromTask(destID, host, itemID);

                   // m_scene.InventoryService.AddItemAsync(agentItem, (itm) =>
                   /*if (agentItem != null)
                    {
                        if (--countLeft == 0)
                        {
                            IScenePresence avatar;
                            if (m_scene.TryGetScenePresence(destID, out avatar))
                            {
                                SendInventoryUpdate(avatar.ControllingClient, rootFolder, true, false);
                                SendInventoryUpdate(avatar.ControllingClient, newFolder, false, true);
                            }
                        }
                    });
                    */
                    agentItem.Folder = newFolderID;
                    m_scene.InventoryService.AddItem(agentItem); 
                }
           // }
      IScenePresence avatar;  
                    if (m_scene.TryGetScenePresence(destID, out avatar))  
                    {  
                        SendInventoryUpdate(avatar.ControllingClient, rootFolder, true, false);  
                        SendInventoryUpdate(avatar.ControllingClient, newFolder, false, true);  
                    }  
               });  

            return newFolderID;
        }
 public bool CheckThreatLevel(ThreatLevel level, string function, ISceneChildEntity m_host, string API,
                              UUID itemID)
 {
     GetDefinition(level).CheckThreatLevel(function, m_host, API);
     return(CheckFunctionLimits(function, m_host, API, itemID));
 }
Example #27
0
 public void TriggerObjectDeGrab (ISceneChildEntity part, ISceneChildEntity child, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
 {
     ObjectDeGrabDelegate handlerObjectDeGrab = OnObjectDeGrab;
     if (handlerObjectDeGrab != null)
     {
         foreach (ObjectDeGrabDelegate d in handlerObjectDeGrab.GetInvocationList ())
         {
             try
             {
                 d (part, child, remoteClient, surfaceArgs);
             }
             catch (Exception e)
             {
                 m_log.ErrorFormat (
                     "[EVENT MANAGER]: Delegate for TriggerObjectDeGrab failed - continuing.  {0} {1}",
                     e.ToString (), e.StackTrace);
             }
         }
     }
 }
        private bool CheckFunctionLimits(string function, ISceneChildEntity m_host, string API, UUID itemID)
        {
            LimitDef d          = null;
            bool     isAPI      = m_functionsToLimit.TryGetValue(API, out d);
            bool     isFunction = m_functionsToLimit.TryGetValue(function, out d); //Function overrides API

            if (m_allowFunctionLimiting && (isAPI || isFunction))
            {
                //Get the list for the given type
                Dictionary <string, LimitReq> functions;
                bool doInsert = false;
                if (d.Type == LimitType.Owner)
                {
                    if (!m_functionLimiting.TryGetValue(m_host.OwnerID, out functions))
                    {
                        doInsert  = true;
                        functions = new Dictionary <string, LimitReq>();
                    }
                }
                else if (d.Type == LimitType.Script)
                {
                    if (!m_functionLimiting.TryGetValue(itemID, out functions))
                    {
                        doInsert  = true;
                        functions = new Dictionary <string, LimitReq>();
                    }
                }
                else if (d.Type == LimitType.Group)
                {
                    if (!m_functionLimiting.TryGetValue(m_host.ParentEntity.UUID, out functions))
                    {
                        doInsert  = true;
                        functions = new Dictionary <string, LimitReq>();
                    }
                }
                else if (d.Type == LimitType.Prim)
                {
                    if (!m_functionLimiting.TryGetValue(m_host.UUID, out functions))
                    {
                        doInsert  = true;
                        functions = new Dictionary <string, LimitReq>();
                    }
                }
                else
                {
                    return(true);
                }

                LimitReq r;
                if (!functions.TryGetValue(function, out r))
                {
                    r = new LimitReq();
                }

                if (d.MaxNumberOfTimes != 0)
                {
                    if (r.NumberOfTimesFired + 1 > d.MaxNumberOfTimes) //Too Many, kill it
                    {
                        TriggerAlert(function, d,
                                     "You have exceeded the number of times this function (" + function +
                                     ") is allowed to be fired",
                                     m_host);
                        return(TriggerAction(d, m_host, itemID));
                    }
                    r.NumberOfTimesFired++;
                }
                if (d.TimeScale != 0)
                {
                    if (r.LastFired != 0 && Util.EnvironmentTickCountSubtract(r.LastFired) < d.TimeScale)
                    {
                        if (r.FunctionsSinceLastFired + 1 > d.FunctionsOverTimeScale)
                        {
                            TriggerAlert(function, d,
                                         "You have fired the given function " + function + " too quickly.", m_host);
                            return(TriggerAction(d, m_host, itemID));
                        }
                    }
                    else
                    {
                        r.LastFired = Util.EnvironmentTickCount();
                        r.FunctionsSinceLastFired = 0; //Clear it out again
                    }
                    r.FunctionsSinceLastFired++;
                }
                //Put it back where it came from
                functions[isFunction ? function : API] = r;
                if (doInsert)
                {
                    if (d.Type == LimitType.Owner)
                    {
                        m_functionLimiting[m_host.OwnerID] = functions;
                    }
                    else if (d.Type == LimitType.Script)
                    {
                        m_functionLimiting[itemID] = functions;
                    }
                    else if (d.Type == LimitType.Group)
                    {
                        m_functionLimiting[m_host.ParentEntity.UUID] = functions;
                    }
                    else if (d.Type == LimitType.Prim)
                    {
                        m_functionLimiting[m_host.UUID] = functions;
                    }
                }
            }
            return(true);
        }
 public void DeleteFrom(ISceneChildEntity Part, UUID ItemID)
 {
     OSDMap component = m_manager.GetComponentState(Part, m_componentName) as OSDMap;
     //Attempt to find the state saves we have
     if (component != null)
     {
         //if we did remove something, resave it
         if (component.Remove(ItemID.ToString()))
         {
             if (component.Count == 0)
                 m_manager.RemoveComponentState(Part.UUID, m_componentName);
             else
                 m_manager.SetComponentState(Part, m_componentName, component);
             Part.ParentEntity.HasGroupChanged = true;
         }
     }
 }
            public void CheckThreatLevel(string function, ISceneChildEntity m_host, string API)
            {
                if (CheckUser(m_host))
                {
                    return;
                }
                List <UUID> FunctionPerms = new List <UUID>();

                if (!m_FunctionPerms.TryGetValue(function, out FunctionPerms))
                {
                    string perm = m_scriptProtectionModule.m_config.GetString("Allow_" + function, "");
                    if (perm == "")
                    {
                        FunctionPerms = null; // a null value is default, which means check against the max threat level
                    }
                    else
                    {
                        bool allowed;

                        if (bool.TryParse(perm, out allowed))
                        {
                            // Boolean given
                            FunctionPerms = allowed ? new List <UUID> {
                                UUID.Zero
                            } : new List <UUID>();
                        }
                        else
                        {
                            FunctionPerms = new List <UUID>();

                            string[] ids = perm.Split(new[] { ',' });

                            foreach (string current in ids.Select(id => id.Trim()))
                            {
                                UUID uuid;

                                if (UUID.TryParse(current, out uuid))
                                {
                                    if (uuid != UUID.Zero)
                                    {
                                        FunctionPerms.Add(uuid);
                                    }
                                }
                            }
                        }
                        m_FunctionPerms[function] = FunctionPerms;
                    }
                }

                // If the list is null, then the value was true / undefined
                // Threat level governs permissions in this case
                //
                // If the list is non-null, then it is a list of UUIDs allowed
                // to use that particular function. False causes an empty
                // list and therefore means "no one"
                //
                // To allow use by anyone, the list contains UUID.Zero
                //
                if (FunctionPerms == null) // No list = true
                {
                    if (m_threatLevel > m_scriptProtectionModule.GetThreatLevel().m_threatLevel)
                    {
                        m_scriptProtectionModule.Error("Runtime Error: ",
                                                       String.Format(
                                                           "{0} permission denied.  Allowed threat level is {1} but function threat level is {2}.",
                                                           function,
                                                           m_scriptProtectionModule.GetThreatLevel().m_threatLevel,
                                                           m_threatLevel));
                    }
                }
                else
                {
                    if (!FunctionPerms.Contains(UUID.Zero))
                    {
                        if (!FunctionPerms.Contains(m_host.OwnerID))
                        {
                            if (m_allowGroupPermissions)
                            {
                                Dictionary <string, bool> cachedFunctions;
                                //Check to see whether we have already evaluated this function for this user
                                if (m_knownAllowedGroupFunctionsForAvatars.TryGetValue(m_host.OwnerID,
                                                                                       out cachedFunctions))
                                {
                                    if (cachedFunctions.ContainsKey(function))
                                    {
                                        if (cachedFunctions[function])
                                        {
                                            return;
                                        }
                                        else
                                        {
                                            m_scriptProtectionModule.Error("Runtime Error: ",
                                                                           String.Format(
                                                                               "{0} permission denied.  Prim owner is not in the list of users allowed to execute this function.",
                                                                               function));
                                        }
                                    }
                                }
                                else
                                {
                                    cachedFunctions = new Dictionary <string, bool>();
                                }
                                IGroupsModule groupsModule =
                                    m_host.ParentEntity.Scene.RequestModuleInterface <IGroupsModule>();
                                if (groupsModule != null)
                                {
                                    bool success = false;
                                    foreach (UUID id in FunctionPerms)
                                    {
                                        if (groupsModule.GroupPermissionCheck(m_host.OwnerID, id, GroupPowers.None))
                                        {
                                            success = true;
                                            break;
                                        }
                                    }
                                    //Cache the success
                                    cachedFunctions[function] = success;
                                    if (!m_knownAllowedGroupFunctionsForAvatars.ContainsKey(m_host.OwnerID))
                                    {
                                        m_knownAllowedGroupFunctionsForAvatars.Add(m_host.OwnerID,
                                                                                   new Dictionary <string, bool>());
                                    }
                                    m_knownAllowedGroupFunctionsForAvatars[m_host.OwnerID] = cachedFunctions;

                                    if (success)
                                    {
                                        return; //All is good
                                    }
                                }
                            }
                            m_scriptProtectionModule.Error("Runtime Error: ",
                                                           String.Format(
                                                               "{0} permission denied.  Prim owner is not in the list of users allowed to execute this function.",
                                                               function));
                        }
                    }
                }
            }
Example #31
0
        public void collision_start (ISceneChildEntity part, ColliderArgs col)
        {
            // Add to queue for all scripts in ObjectID object
            List<DetectParams> det = new List<DetectParams>();

            foreach (DetectedObject detobj in col.Colliders)
            {
                DetectParams d = new DetectParams();
                d.Key = detobj.keyUUID;
                d.Populate(part.ParentEntity.Scene);
                d.LinkNum = part.LinkNum;
                det.Add(d);
            }

            if (det.Count > 0)
            {
                ScriptData[] datas = ScriptEngine.ScriptProtection.GetScripts(part.UUID);

                if (datas == null || datas.Length == 0)
                {
                    //datas = ScriptEngine.ScriptProtection.GetScripts(part.ParentGroup.RootPart.UUID);
                    //if (datas == null || datas.Length == 0)
                        return;
                }
                string functionName = "collision_start";
                object[] param = new Object[] { new LSL_Types.LSLInteger(det.Count) };

                foreach (ScriptData ID in datas)
                {
                    if (CheckIfEventShouldFire(ID, functionName, param))
                        m_scriptEngine.AddToScriptQueue(ID, functionName, det.ToArray(), EventPriority.FirstStart, param);
                }
            }
        }
Example #32
0
        /// <summary>
        ///     This deals with saving the report into the database.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="regionName"></param>
        /// <param name="abuserID"></param>
        /// <param name="catagory"></param>
        /// <param name="checkflags"></param>
        /// <param name="details"></param>
        /// <param name="objectID"></param>
        /// <param name="position"></param>
        /// <param name="reportType"></param>
        /// <param name="screenshotID"></param>
        /// <param name="summery"></param>
        /// <param name="reporter"></param>
        private void UserReport(IClientAPI client, string regionName, UUID abuserID, byte catagory, byte checkflags,
                                string details, UUID objectID, Vector3 position, byte reportType, UUID screenshotID,
                                string summery, UUID reporter)
        {
            AbuseReport report = new AbuseReport
            {
                ObjectUUID     = objectID,
                ObjectPosition = position.ToString(),
                Active         = true,
                Checked        = false,
                Notes          = "",
                AssignedTo     = "No One",
                ScreenshotID   = screenshotID
            };

            if (objectID != UUID.Zero)
            {
                ISceneChildEntity Object = client.Scene.GetSceneObjectPart(objectID);
                report.ObjectName = Object.Name;
            }
            else
            {
                report.ObjectName = "";
            }

            string[] detailssplit = details.Split('\n');

            string AbuseDetails = detailssplit[detailssplit.Length - 1];

            report.AbuseDetails = AbuseDetails;

            report.ReporterName = client.Name;

            string[] findRegion = summery.Split('|');
            report.RegionName = findRegion[1];

            string[] findLocation    = summery.Split('(');
            string[] findLocationend = findLocation[1].Split(')');
            report.AbuseLocation = findLocationend[0];

            string[] findCategory    = summery.Split('[');
            string[] findCategoryend = findCategory[1].Split(']');
            report.Category = findCategoryend[0];

            string[] findAbuserName    = summery.Split('{');
            string[] findAbuserNameend = findAbuserName[1].Split('}');
            report.AbuserName = findAbuserNameend[0];

            string[] findSummary = summery.Split('\"');

            string abuseSummary = findSummary[1];

            if (findSummary.Length != 0)
            {
                abuseSummary = findSummary[1];
            }

            report.AbuseSummary = abuseSummary;


            report.Number = (-1);

            EstateSettings ES = client.Scene.RegionInfo.EstateSettings;

            //If the abuse email is set up and the email module is available, send the email
            if (ES.AbuseEmailToEstateOwner && ES.AbuseEmail != "")
            {
                IEmailModule Email = m_Scene.RequestModuleInterface <IEmailModule>();
                if (Email != null)
                {
                    Email.SendEmail(UUID.Zero, ES.AbuseEmail, "Abuse Report", "This abuse report was submitted by " +
                                    report.ReporterName + " against " +
                                    report.AbuserName + " at " +
                                    report.AbuseLocation + " in your region " +
                                    report.RegionName +
                                    ". Summary: " + report.AbuseSummary +
                                    ". Details: " + report.AbuseDetails + ".",
                                    client.Scene);
                }
            }
            //Tell the DB about it
            IAbuseReports conn = m_Scene.RequestModuleInterface <IAbuseReports>();

            if (conn != null)
            {
                conn.AddAbuseReport(report);
            }
        }
Example #33
0
/*
 *      public override PhysicsActor AddPrim(Vector3 position, Vector3 size, Quaternion rotation)
 *      {
 *          return null;
 *      }
 */

        public override PhysicsObject AddPrimShape(ISceneChildEntity entity)
        {
            return(null);
        }
Example #34
0
 public bool TryGetPart(UUID objectUUID, out ISceneChildEntity SensedObject)
 {
     return(m_sceneGraph.TryGetPart(objectUUID, out SensedObject));
 }
Example #35
0
        public ISceneEntity GetRezReadySceneObject(TaskInventoryItem item)
        {
            byte [] rezAsset = m_part.ParentGroup.Scene.AssetService.GetData(item.AssetID.ToString());

            if (null == rezAsset)
            {
                MainConsole.Instance.WarnFormat(
                    "[Prim Inventory]: Could not find asset {0} for inventory item {1} in {2}",
                    item.AssetID, item.Name, m_part.Name);
                return(null);
            }

            string       xmlData = Utils.BytesToString(rezAsset);
            ISceneEntity group   = SceneEntitySerializer.SceneObjectSerializer.FromOriginalXmlFormat(xmlData,
                                                                                                     m_part.ParentGroup
                                                                                                     .Scene);

            if (group == null)
            {
                return(null);
            }

            group.IsDeleted = false;
            foreach (ISceneChildEntity part in group.ChildrenEntities())
            {
                part.IsLoading = false;
            }
            //Reset IDs, etc
            m_part.ParentGroup.Scene.SceneGraph.PrepPrimForAdditionToScene(group);

            ISceneChildEntity rootPart = group.GetChildPart(group.UUID);

            // Since renaming the item in the inventory does not affect the name stored
            // in the serialization, transfer the correct name from the inventory to the
            // object itself before we rez.
            rootPart.Name        = item.Name;
            rootPart.Description = item.Description;

            List <ISceneChildEntity> partList = group.ChildrenEntities();

            group.SetGroup(m_part.GroupID, group.OwnerID, false);

            if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0)
            {
                if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions())
                {
                    foreach (ISceneChildEntity part in partList)
                    {
                        part.EveryoneMask  = item.EveryonePermissions;
                        part.NextOwnerMask = item.NextPermissions;
                    }

                    group.ApplyNextOwnerPermissions();
                }
            }

            foreach (ISceneChildEntity part in partList)
            {
                if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0)
                {
                    part.LastOwnerID = part.OwnerID;
                    part.OwnerID     = item.OwnerID;
                    part.Inventory.ChangeInventoryOwner(item.OwnerID);
                }

                part.EveryoneMask  = item.EveryonePermissions;
                part.NextOwnerMask = item.NextPermissions;
            }

            rootPart.TrimPermissions();

            return(group);
        }
Example #36
0
        public void CheckThreatLevel(ThreatLevel level, string function, ISceneChildEntity m_host, string API)
        {
            List <UUID> FunctionPerms = new List <UUID>();

            if (!m_FunctionPerms.TryGetValue(function, out FunctionPerms))
            {
                string perm = m_config.GetString("Allow_" + function, "");
                if (perm == "")
                {
                    FunctionPerms = null;// a null value is default
                }
                else
                {
                    bool allowed;

                    if (bool.TryParse(perm, out allowed))
                    {
                        // Boolean given
                        if (allowed)
                        {
                            FunctionPerms = new List <UUID>();
                            FunctionPerms.Add(UUID.Zero);
                        }
                        else
                        {
                            FunctionPerms = new List <UUID>(); // Empty list = none
                        }
                    }
                    else
                    {
                        FunctionPerms = new List <UUID>();

                        string[] ids = perm.Split(new char[] { ',' });
                        foreach (string id in ids)
                        {
                            string current = id.Trim();
                            UUID   uuid;

                            if (UUID.TryParse(current, out uuid))
                            {
                                if (uuid != UUID.Zero)
                                {
                                    FunctionPerms.Add(uuid);
                                }
                            }
                        }
                    }
                    m_FunctionPerms[function] = FunctionPerms;
                }
            }

            // If the list is null, then the value was true / undefined
            // Threat level governs permissions in this case
            //
            // If the list is non-null, then it is a list of UUIDs allowed
            // to use that particular function. False causes an empty
            // list and therefore means "no one"
            //
            // To allow use by anyone, the list contains UUID.Zero
            //
            if (FunctionPerms == null) // No list = true
            {
                if (level > m_MaxThreatLevel)
                {
                    Error("Runtime Error: ",
                          String.Format(
                              "{0} permission denied.  Allowed threat level is {1} but function threat level is {2}.",
                              function, m_MaxThreatLevel, level));
                }
            }
            else
            {
                if (!FunctionPerms.Contains(UUID.Zero))
                {
                    if (!FunctionPerms.Contains(m_host.OwnerID))
                    {
                        Error("Runtime Error: ",
                              String.Format("{0} permission denied.  Prim owner is not in the list of users allowed to execute this function.",
                                            function));
                    }
                }
            }
        }
Example #37
0
        public virtual void TriggerSound(
            UUID soundId, UUID ownerID, UUID objectID, UUID parentID, double gain, Vector3 position, UInt64 handle,
            float radius)
        {
            bool                    LocalOnly        = false;
            ILandObject             ILO              = null;
            IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface <IParcelManagementModule>();

            if (parcelManagement != null)
            {
                ILO = parcelManagement.GetLandObject(position.X, position.Y);
                if (ILO != null) //Check only if null, otherwise this breaks megaregions
                {
                    LocalOnly = (ILO.LandData.Flags & (uint)ParcelFlags.SoundLocal) == (uint)ParcelFlags.SoundLocal;
                }
            }
            ISceneChildEntity part = m_scene.GetSceneObjectPart(objectID);

            if (part == null)
            {
                IScenePresence sp;
                if (!m_scene.TryGetScenePresence(objectID, out sp))
                {
                    return;
                }
            }
            else
            {
                ISceneEntity grp = part.ParentEntity;

                if (grp.IsAttachment && grp.GetAttachmentPoint() > 30)
                {
                    objectID = ownerID;
                    parentID = ownerID;
                }
            }

            m_scene.ForEachScenePresence(delegate(IScenePresence sp)
            {
                if (Cones.Count != 0)
                {
                    foreach (ConeOfSilence CS in Cones.Values)
                    {
                        if (Util.GetDistanceTo(sp.AbsolutePosition, CS.Position) >
                            CS.Radius)
                        {
                            // Presence is outside of the Cone of silence

                            if (Util.GetDistanceTo(CS.Position, position) < CS.Radius)
                            {
                                //Sound was triggered inside the cone, but avatar is outside
                                continue;
                            }
                        }
                        else
                        {
                            // Avatar is inside the cone of silence
                            if (Util.GetDistanceTo(CS.Position, position) > CS.Radius)
                            {
                                //Sound was triggered outside of the cone, but avatar is inside of the cone.
                                continue;
                            }
                        }
                    }
                }
                if (sp.IsChildAgent)
                {
                    return;
                }

                float dis = (float)Util.GetDistanceTo(sp.AbsolutePosition, position);
                if (dis > 100.0f)                                  // Max audio distance
                {
                    return;
                }

                //Check to see if the person is local and the av is in the same parcel
                if (LocalOnly && sp.CurrentParcelUUID != ILO.LandData.GlobalID)
                {
                    return;
                }

                // Scale by distance
                float thisSPGain;
                if (radius == 0)
                {
                    thisSPGain = (float)(gain * ((100.0f - dis) / 100.0f));
                }
                else
                {
                    thisSPGain = (float)(gain * ((radius - dis) / radius));
                }

                sp.ControllingClient.SendTriggeredSound(
                    soundId, ownerID, objectID, parentID, handle, position,
                    thisSPGain);
            });
        }
Example #38
0
            public void PhysicsActor_OnCollisionUpdate(EventArgs e)
            {
                if (m_SP == null || m_SP.Scene == null || m_SP.Invulnerable || HasLeftCombat || e == null)
                {
                    return;
                }

                CollisionEventUpdate            collisionData = (CollisionEventUpdate)e;
                Dictionary <uint, ContactPoint> coldata       = collisionData.GetCollisionEvents();

                float          starthealth   = Health;
                IScenePresence killingAvatar = null;

                foreach (uint localid in coldata.Keys)
                {
                    ISceneChildEntity part        = m_SP.Scene.GetSceneObjectPart(localid);
                    IScenePresence    otherAvatar = null;
                    if (part != null && part.ParentEntity.Damage > 0)
                    {
                        otherAvatar = m_SP.Scene.GetScenePresence(part.OwnerID);
                        ICombatPresence OtherAvatarCP = otherAvatar == null
                                                            ? null
                                                            : otherAvatar.RequestModuleInterface <ICombatPresence>();
                        if (OtherAvatarCP != null && OtherAvatarCP.HasLeftCombat)
                        {
                            // If the avatar is null, the person is not inworld, and not on a team
                            //If they have left combat, do not let them cause any damage.
                            continue;
                        }

                        //Check max damage to inflict
                        if (part.ParentEntity.Damage > m_combatModule.MaximumDamageToInflict)
                        {
                            part.ParentEntity.Damage = m_combatModule.MaximumDamageToInflict;
                        }

                        // If the avatar is null, the person is not inworld, and not on a team
                        if (m_combatModule.AllowTeams && OtherAvatarCP != null && otherAvatar.UUID != m_SP.UUID &&
                            OtherAvatarCP.Team == Team)
                        {
                            float Hits = 0;
                            if (!TeamHits.TryGetValue(otherAvatar.UUID, out Hits))
                            {
                                Hits = 0;
                            }
                            Hits++;
                            if (m_combatModule.SendTeamKillerInfo && Hits == m_combatModule.TeamHitsBeforeSend)
                            {
                                otherAvatar.ControllingClient.SendAlertMessage("You have shot too many teammates and " +
                                                                               m_combatModule.DamageToTeamKillers +
                                                                               " health has been taken from you!");
                                OtherAvatarCP.IncurDamage(null, m_combatModule.DamageToTeamKillers);
                                Hits = 0;
                            }
                            TeamHits[otherAvatar.UUID] = Hits;

                            if (m_combatModule.AllowTeamKilling) //Green light on team killing
                            {
                                Health -= part.ParentEntity.Damage;
                            }
                        }
                        else //Object, hit em
                        {
                            Health -= part.ParentEntity.Damage;
                        }
                    }
                    else
                    {
                        float Z = m_SP.Velocity.Length();
                        if (coldata[localid].PenetrationDepth >= 0.05f && m_SP.Velocity.Z < -3 &&
                            !m_SP.PhysicsActor.Flying && !m_SP.PhysicsActor.IsJumping)
                        {
                            Z = Math.Max(Z, 1.5f) * 10;
                            float damage = Math.Min(coldata[localid].PenetrationDepth, 15f);
                            Health -= damage * Z;
                        }
                    }

                    if (Health > m_combatModule.MaximumHealth)
                    {
                        Health = m_combatModule.MaximumHealth;
                    }

                    if (Health <= 0 && killingAvatar == null)
                    {
                        killingAvatar = otherAvatar;
                    }
                    //MainConsole.Instance.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString());
                }

                if (starthealth != Health)
                {
                    m_SP.ControllingClient.SendHealth(Health);
                }

                if (Health <= 0)
                {
                    KillAvatar(killingAvatar, "You killed " + m_SP.Name, "You died!", true, true);
                }
            }
Example #39
0
        /// <summary>
        ///     Invoked when the client selects a prim.
        /// </summary>
        /// <param name="primLocalIDs"></param>
        /// <param name="remoteClient"></param>
        protected void SelectPrim(List <uint> primLocalIDs, IClientAPI remoteClient)
        {
            IScene scene = remoteClient.Scene;
            List <ISceneChildEntity> EntitiesToUpdate = new List <ISceneChildEntity>();
            ISceneChildEntity        prim             = null;

            foreach (uint primLocalID in primLocalIDs)
            {
                ISceneChildEntity entity = null;
                if (scene.SceneGraph.TryGetPart(primLocalID, out entity))
                {
                    if (entity is ISceneChildEntity)
                    {
                        prim = entity;
                        // changed so that we send select to all the indicated prims
                        // also to root prim (done in prim.IsSelected)
                        // so "edit link parts" keep the object select and not moved by physics
                        // similar changes on deselect
                        // part.IsSelect is on SceneObjectPart.cs
                        // Ubit
                        prim.ParentEntity.IsSelected = true;
                    }
                }
                //Check for avies! They arn't prims!
                if (scene.GetScenePresence(primLocalID) != null)
                {
                    continue;
                }

                if (entity != null)
                {
                    if (!EntitiesToUpdate.Contains(entity))
                    {
                        EntitiesToUpdate.Add(entity);
                    }
                }
                else
                {
                    MainConsole.Instance.ErrorFormat(
                        "[SCENEPACKETHANDLER]: Could not find prim {0} in SelectPrim, killing prim.",
                        primLocalID);
                    //Send a kill packet to the viewer so it doesn't come up again
                    remoteClient.SendKillObject(scene.RegionInfo.RegionHandle, new uint[1] {
                        primLocalID
                    });
                }
            }
            IScenePresence SP;

            scene.TryGetScenePresence(remoteClient.AgentId, out SP);
            if (SP == null)
            {
                return;
            }
            if (EntitiesToUpdate.Count != 0)
            {
                SP.SceneViewer.QueuePartsForPropertiesUpdate(EntitiesToUpdate.ToArray());
            }
            PerClientSelectionParticles selection = SP.RequestModuleInterface <PerClientSelectionParticles>();

            if (selection != null)
            {
                selection.SelectedUUID = prim;
                selection.IsSelecting  = true;
            }
        }
Example #40
0
        public virtual void PlayAttachedSound(
            UUID soundID, UUID ownerID, UUID objectID, double gain, Vector3 position, byte flags, float radius)
        {
            ISceneChildEntity part = m_scene.GetSceneObjectPart(objectID);

            if (part == null)
            {
                return;
            }

            bool                    LocalOnly        = false;
            ILandObject             ILO              = null;
            IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface <IParcelManagementModule>();

            if (parcelManagement != null)
            {
                ILO = parcelManagement.GetLandObject(position.X, position.Y);
                if (ILO != null)
                {
                    LocalOnly = (ILO.LandData.Flags & (uint)ParcelFlags.SoundLocal) == (uint)ParcelFlags.SoundLocal;
                }
            }

            m_scene.ForEachScenePresence(delegate(IScenePresence sp)
            {
                if (Cones.Count != 0)
                {
                    foreach (ConeOfSilence CS in Cones.Values)
                    {
                        if (Util.GetDistanceTo(sp.AbsolutePosition, CS.Position) >
                            CS.Radius)
                        {
                            // Presence is outside of the Cone of silence
                            if (Util.GetDistanceTo(CS.Position, position) < CS.Radius)
                            {
                                //Sound was triggered inside the cone, but avatar is outside
                                continue;
                            }
                        }
                        else
                        {
                            // Avatar is inside the cone of silence
                            if (Util.GetDistanceTo(CS.Position, position) > CS.Radius)
                            {
                                //Sound was triggered outside of the cone, but avatar is inside of the cone.
                                continue;
                            }
                        }
                    }
                }
                if (sp.IsChildAgent)
                {
                    return;
                }

                double dis = Util.GetDistanceTo(sp.AbsolutePosition, position);
                if (dis > 100.0)                                  // Max audio distance
                {
                    return;
                }

                if (part.IsAttachment)
                {
                    if (part.ParentEntity.GetAttachmentPoint() >=
                        (uint)OpenMetaverse.AttachmentPoint.HUDCenter2 &&
                        part.ParentEntity.GetAttachmentPoint() <=
                        (uint)OpenMetaverse.AttachmentPoint.HUDBottomRight)                                   // HUD
                    {
                        if (sp.ControllingClient.AgentId != part.OwnerID)
                        {
                            return;
                        }
                    }

                    if (sp.ControllingClient.AgentId == part.OwnerID)
                    {
                        dis = 0;
                    }
                }

                //Check to see if the person is local and the av is in the same parcel
                if (LocalOnly && sp.CurrentParcelUUID != ILO.LandData.GlobalID)
                {
                    return;
                }

                if ((sp.CurrentParcelUUID != ILO.LandData.GlobalID &&
                     (sp.CurrentParcel.LandData.Private || ILO.LandData.Private)))
                {
                    return;
                }
                //If one of them is in a private parcel, and the other isn't in the same parcel, don't send the chat message

                float thisSpGain;

                // Scale by distance
                if (radius == 0)
                {
                    thisSpGain = (float)((double)gain * ((100.0 - dis) / 100.0));
                }
                else
                {
                    thisSpGain = (float)((double)gain * ((radius - dis) / radius));
                }

                if (sp.Scene.GetSceneObjectPart(objectID).UseSoundQueue == 1 &&
                    (flags & (int)SoundFlags.Queue) == 0)
                {
                    flags |= (int)SoundFlags.Queue;
                }

                sp.ControllingClient.SendPlayAttachedSound(soundID, objectID, ownerID,
                                                           thisSpGain, flags);
            });
        }
Example #41
0
        void CreatePrim(WarpRenderer renderer, ISceneChildEntity prim)
        {
            try {
                if ((PCode)prim.Shape.PCode != PCode.Prim)
                {
                    return;
                }
                if (prim.Scale.LengthSquared() < MIN_PRIM_SIZE * MIN_PRIM_SIZE)
                {
                    return;
                }

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

                // Are we dealing with a sculptie or mesh?
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetching the asset
                    byte [] sculptAsset = m_scene.AssetService.GetData(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);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
                            meshAsset = null;
                        }
                        else   // It's sculptie
                        {
                            Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset);
                            if (sculpt != null)
                            {
                                renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
                                                                                    DetailLevel.Medium);
                                sculpt.Dispose();
                            }
                        }
                        sculptAsset = null;
                    }
                    else
                    {
                        // missing sculpt data... replace with something
                        renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
                    }
                }
                else   // Prim
                {
                    renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
                }

                if (renderMesh == null)
                {
                    return;
                }

                warp_Vector     primPos = ConvertVector(prim.GetWorldPosition());
                warp_Quaternion primRot = ConvertQuaternion(prim.GetRotationOffset());

                warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);

                if (prim.ParentID != 0)
                {
                    ISceneEntity group = m_scene.GetGroupByPrim(prim.LocalId);
                    if (group != null)
                    {
                        m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootChild.GetRotationOffset())));
                    }
                }

                warp_Vector primScale = ConvertVector(prim.Scale);

                string primID = prim.UUID.ToString();

                // Create the prim faces
                for (int i = 0; i < renderMesh.Faces.Count; i++)
                {
                    Face   renderFace = renderMesh.Faces [i];
                    string meshName   = primID + "-Face-" + i;

                    warp_Object faceObj = new warp_Object(renderFace.Vertices.Count, renderFace.Indices.Count / 3);

                    foreach (Vertex v in renderFace.Vertices)
                    {
                        warp_Vector pos  = ConvertVector(v.Position);
                        warp_Vector norm = ConvertVector(v.Normal);

                        if (prim.Shape.SculptTexture == UUID.Zero)
                        {
                            norm = norm.reverse();
                        }
                        warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);

                        faceObj.addVertex(vert);
                    }

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

                    Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                    string materialName;
                    Color4 faceColor = GetFaceColor(teFace);

                    if (m_texturePrims && (prim.Scale.LengthSquared() > m_texturePrimSize))
                    {
                        materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
                    }
                    else
                    {
                        materialName = GetOrCreateMaterial(renderer, faceColor);
                    }

                    faceObj.transform(m);
                    faceObj.setPos(primPos);
                    faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);

                    renderer.Scene.addObject(meshName, faceObj);

                    renderer.SetObjectMaterial(meshName, materialName);

                    faceObj = null;
                }
                renderMesh.Faces.Clear();
                renderMesh = null;
            } catch (Exception ex) {
                MainConsole.Instance.Warn("[Warp3D]: Exception creating prim, " + ex);
            }
        }
Example #42
0
        private List <SensedEntity> doObjectSensor(SenseRepeatClass ts)
        {
            List <ISceneEntity> Entities;
            List <SensedEntity> sensedEntities = new List <SensedEntity>();

            ISceneChildEntity SensePoint = ts.host;

            Vector3 fromRegionPos = SensePoint.AbsolutePosition;

            // If this is an object sense by key try to get it directly
            // rather than getting a list to scan through
            if (ts.keyID != UUID.Zero)
            {
                IEntity e = null;
                ts.host.ParentEntity.Scene.Entities.TryGetValue(ts.keyID, out e);
                if (e == null || !(e is ISceneEntity))
                {
                    return(sensedEntities);
                }
                Entities = new List <ISceneEntity> ();
                Entities.Add(e as ISceneEntity);
            }
            else
            {
                Entities = new List <ISceneEntity> (ts.host.ParentEntity.Scene.Entities.GetEntities(fromRegionPos, (float)ts.range));
            }

            // pre define some things to avoid repeated definitions in the loop body
            Vector3         toRegionPos;
            double          dis;
            int             objtype;
            SceneObjectPart part;
            float           dx;
            float           dy;
            float           dz;

            Quaternion q = SensePoint.RotationOffset;

            if (SensePoint.ParentEntity.RootChild.IsAttachment)
            {
                // In attachments, the sensor cone always orients with the
                // avatar rotation. This may include a nonzero elevation if
                // in mouselook.

                IScenePresence avatar = ts.host.ParentEntity.Scene.GetScenePresence(SensePoint.ParentEntity.RootChild.AttachedAvatar);
                q = avatar.Rotation;
            }
            LSL_Types.Quaternion r           = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
            LSL_Types.Vector3    forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
            double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);

            Vector3 ZeroVector = new Vector3(0, 0, 0);

            bool nameSearch = (ts.name != null && ts.name != "");

            foreach (ISceneEntity ent in Entities)
            {
                bool keep = true;

                if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search
                {
                    continue;
                }

                if (ent.IsDeleted) // taken so long to do this it has gone from the scene
                {
                    continue;
                }

                if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar
                {
                    continue;
                }
                toRegionPos = ent.AbsolutePosition;

                // Calculation is in line for speed
                dx = toRegionPos.X - fromRegionPos.X;
                dy = toRegionPos.Y - fromRegionPos.Y;
                dz = toRegionPos.Z - fromRegionPos.Z;

                // Weed out those that will not fit in a cube the size of the range
                // no point calculating if they are within a sphere the size of the range
                // if they arent even in the cube
                if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range)
                {
                    dis = ts.range + 1.0;
                }
                else
                {
                    dis = Math.Sqrt(dx * dx + dy * dy + dz * dz);
                }

                if (keep && dis <= ts.range && ts.host.UUID != ent.UUID)
                {
                    // In Range and not the object containing the script, is it the right Type ?
                    objtype = 0;

                    part = ((SceneObjectGroup)ent).RootPart;
                    if (part.AttachmentPoint != 0) // Attached so ignore
                    {
                        continue;
                    }

                    if (part.Inventory.ContainsScripts())
                    {
                        objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ...
                    }
                    else
                    {
                        if (ent.Velocity.Equals(ZeroVector))
                        {
                            objtype |= PASSIVE; // Passive non-moving
                        }
                        else
                        {
                            objtype |= ACTIVE; // moving so active
                        }
                    }

                    // If any of the objects attributes match any in the requested scan type
                    if (((ts.type & objtype) != 0))
                    {
                        // Right type too, what about the other params , key and name ?
                        if (ts.arc < Math.PI)
                        {
                            // not omni-directional. Can you see it ?
                            // vec forward_dir = llRot2Fwd(llGetRot())
                            // vec obj_dir = toRegionPos-fromRegionPos
                            // dot=dot(forward_dir,obj_dir)
                            // mag_fwd = mag(forward_dir)
                            // mag_obj = mag(obj_dir)
                            // ang = acos(dot /(mag_fwd*mag_obj))
                            double ang_obj = 0;
                            try
                            {
                                Vector3           diff    = toRegionPos - fromRegionPos;
                                LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
                                double            dot     = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
                                double            mag_obj = LSL_Types.Vector3.Mag(obj_dir);
                                ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
                            }
                            catch
                            {
                            }

                            if (ang_obj > ts.arc)
                            {
                                keep = false;
                            }
                        }

                        if (keep == true)
                        {
                            // add distance for sorting purposes later
                            sensedEntities.Add(new SensedEntity(dis, ent.UUID));
                        }
                    }
                }
            }
            return(sensedEntities);
        }
Example #43
0
        /// <summary>
        /// Move the given item from the object task inventory to the agent's inventory
        /// </summary>
        /// <param name="avatarId"></param>
        /// <param name="folderId">
        /// The user inventory folder to move (or copy) the item to.  If null, then the most
        /// suitable system folder is used (e.g. the Objects folder for objects).  If there is no suitable folder, then
        /// the item is placed in the user's root inventory folder
        /// </param>
        /// <param name="part"></param>
        /// <param name="itemId"></param>
        /// <param name="checkPermissions"></param>
        public InventoryItemBase MoveTaskInventoryItemToUserInventory (UUID avatarId, UUID folderId, ISceneChildEntity part, UUID itemId, bool checkPermissions)
        {
            IScenePresence avatar;

            if (m_scene.TryGetScenePresence(avatarId, out avatar))
            {
                return MoveTaskInventoryItemToUserInventory (avatar.ControllingClient, folderId, part, itemId, checkPermissions);
            }
            InventoryItemBase agentItem = CreateAgentInventoryItemFromTask(avatarId, part, itemId);

            if (agentItem == null)
                return null;

            agentItem.Folder = folderId;

            AddInventoryItem(agentItem);

            return agentItem;
        }
Example #44
0
        private List <SensedEntity> doAgentSensor(SenseRepeatClass ts)
        {
            List <SensedEntity> sensedEntities = new List <SensedEntity>();

            // If nobody about quit fast
            IEntityCountModule entityCountModule = ts.host.ParentEntity.Scene.RequestModuleInterface <IEntityCountModule> ();

            if (entityCountModule != null && entityCountModule.RootAgents == 0)
            {
                return(sensedEntities);
            }

            ISceneChildEntity SensePoint    = ts.host;
            Vector3           fromRegionPos = SensePoint.AbsolutePosition;
            Quaternion        q             = SensePoint.RotationOffset;

            LSL_Types.Quaternion r           = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
            LSL_Types.Vector3    forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
            double  mag_fwd  = LSL_Types.Vector3.Mag(forward_dir);
            bool    attached = (SensePoint.AttachmentPoint != 0);
            Vector3 toRegionPos;
            double  dis;

            Action <IScenePresence> senseEntity = new Action <IScenePresence>(delegate(IScenePresence presence)
            {
                if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0)
                {
                    return;
                }

                // if the object the script is in is attached and the avatar is the owner
                // then this one is not wanted
                if (attached && presence.UUID == SensePoint.OwnerID)
                {
                    return;
                }

                toRegionPos = presence.AbsolutePosition;
                dis         = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos));

                // are they in range
                if (dis <= ts.range)
                {
                    // Are they in the required angle of view
                    if (ts.arc < Math.PI)
                    {
                        // not omni-directional. Can you see it ?
                        // vec forward_dir = llRot2Fwd(llGetRot())
                        // vec obj_dir = toRegionPos-fromRegionPos
                        // dot=dot(forward_dir,obj_dir)
                        // mag_fwd = mag(forward_dir)
                        // mag_obj = mag(obj_dir)
                        // ang = acos(dot /(mag_fwd*mag_obj))
                        double ang_obj = 0;
                        try
                        {
                            Vector3 diff = toRegionPos - fromRegionPos;
                            LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
                            double dot     = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
                            double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
                            ang_obj        = Math.Acos(dot / (mag_fwd * mag_obj));
                        }
                        catch
                        {
                        }
                        if (ang_obj <= ts.arc)
                        {
                            sensedEntities.Add(new SensedEntity(dis, presence.UUID));
                        }
                    }
                    else
                    {
                        sensedEntities.Add(new SensedEntity(dis, presence.UUID));
                    }
                }
            });

            // If this is an avatar sense by key try to get them directly
            // rather than getting a list to scan through
            if (ts.keyID != UUID.Zero)
            {
                IScenePresence sp;
                // Try direct lookup by UUID
                if (!ts.host.ParentEntity.Scene.TryGetScenePresence(ts.keyID, out sp))
                {
                    return(sensedEntities);
                }
                senseEntity(sp);
            }
            else if (ts.name != null && ts.name != "")
            {
                IScenePresence sp;
                // Try lookup by name will return if/when found
                if (!ts.host.ParentEntity.Scene.TryGetAvatarByName(ts.name, out sp))
                {
                    return(sensedEntities);
                }
                senseEntity(sp);
            }
            else
            {
                ts.host.ParentEntity.Scene.ForEachScenePresence(senseEntity);
            }
            return(sensedEntities);
        }
Example #45
0
 public void TriggerOnScriptMovingEndEvent (ISceneChildEntity part)
 {
     ScriptMovingEndEvent handlerScriptMovingEndEvent = OnScriptMovingEndEvent;
     if (handlerScriptMovingEndEvent != null)
     {
         foreach (ScriptMovingEndEvent d in handlerScriptMovingEndEvent.GetInvocationList ())
         {
             try
             {
                 d (part);
             }
             catch (Exception e)
             {
                 m_log.ErrorFormat (
                     "[EVENT MANAGER]: Delegate for TriggerOnScriptMovingEndEvent failed - continuing.  {0} {1}",
                     e.ToString (), e.StackTrace);
             }
         }
     }
 }
Example #46
0
        public void Populate(IScene scene)
        {
            ISceneChildEntity part = scene.GetSceneObjectPart(Key);
            Vector3           tmp;

            if (part == null) // Avatar, maybe?
            {
                IScenePresence presence = scene.GetScenePresence(Key);
                if (presence == null)
                {
                    return;
                }

                Name  = presence.Name;
                Owner = Key;

                tmp      = presence.AbsolutePosition;
                Position = new LSL_Types.Vector3(
                    tmp.X,
                    tmp.Y,
                    tmp.Z);
                Quaternion rtmp = presence.Rotation;
                Rotation = new LSL_Types.Quaternion(
                    rtmp.X,
                    rtmp.Y,
                    rtmp.Z,
                    rtmp.W);
                tmp      = presence.Velocity;
                Velocity = new LSL_Types.Vector3(
                    tmp.X,
                    tmp.Y,
                    tmp.Z);

                Type = 0x01; // Avatar
                if (presence.Velocity != Vector3.Zero)
                {
                    Type |= 0x02; // Active
                }
                Group = presence.ControllingClient.ActiveGroupId;

                return;
            }

            part = part.ParentEntity.RootChild; // We detect objects only

            LinkNum = 0;                        // Not relevant

            Group = part.GroupID;
            Name  = part.Name;
            Owner = part.OwnerID;
            Type  = part.Velocity == Vector3.Zero ? 0x04 : 0x02;

            foreach (ISceneChildEntity child in part.ParentEntity.ChildrenEntities())
            {
                if (child.Inventory.ContainsScripts())
                {
                    Type |= 0x08; // Scripted
                }
            }
            tmp      = part.AbsolutePosition;
            Position = new LSL_Types.Vector3(tmp.X,
                                             tmp.Y,
                                             tmp.Z);

            Quaternion wr = part.ParentEntity.GroupRotation;
            Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W);

            tmp      = part.Velocity;
            Velocity = new LSL_Types.Vector3(tmp.X,
                                             tmp.Y,
                                             tmp.Z);
        }
Example #47
0
 public void TriggerRezScripts (ISceneChildEntity part, TaskInventoryItem[] taskInventoryItem, int startParam, bool postOnRez, int stateSource, UUID RezzedFrom)
 {
     NewRezScripts handlerRezScripts = OnRezScripts;
     if (handlerRezScripts != null)
     {
         foreach (NewRezScripts d in handlerRezScripts.GetInvocationList ())
         {
             try
             {
                 d (part, taskInventoryItem, startParam, postOnRez, stateSource, RezzedFrom);
             }
             catch (Exception e)
             {
                 m_log.ErrorFormat (
                     "[EVENT MANAGER]: Delegate for TriggerRezScript failed - continuing.  {0} {1}",
                     e.ToString (), e.StackTrace);
             }
         }
     }
 }
Example #48
0
 public void SetSceneRefs(IScene scene, ISceneChildEntity child, bool useStateSaves)
 {
     Scene           = scene;
     Object          = child;
     m_useStateSaves = useStateSaves;
 }
Example #49
0
 public void TriggerScriptLandCollidingEnd (ISceneChildEntity part, ColliderArgs colliders)
 {
     ScriptColliding handlerLandCollidingEnd = OnScriptLandColliderEnd;
     if (handlerLandCollidingEnd != null)
     {
         foreach (ScriptColliding d in handlerLandCollidingEnd.GetInvocationList ())
         {
             try
             {
                 d (part, colliders);
             }
             catch (Exception e)
             {
                 m_log.ErrorFormat (
                     "[EVENT MANAGER]: Delegate for TriggerScriptLandCollidingEnd failed - continuing.  {0} {1}",
                     e.ToString (), e.StackTrace);
             }
         }
     }
 }
Example #50
0
 /// <summary>
 /// Start multiple scripts in the object
 /// </summary>
 /// <param name="part"></param>
 /// <param name="items"></param>
 /// <param name="startParam"></param>
 /// <param name="postOnRez"></param>
 /// <param name="engine"></param>
 /// <param name="stateSource"></param>
 /// <param name="RezzedFrom"></param>
 public void rez_scripts(ISceneChildEntity part, TaskInventoryItem[] items,
         int startParam, bool postOnRez, StateSource stateSource, UUID RezzedFrom)
 {
     List<LUStruct> ItemsToStart = new List<LUStruct>();
     foreach (TaskInventoryItem item in items)
     {
         LUStruct itemToQueue = m_scriptEngine.StartScript(part, item.ItemID,
                 startParam, postOnRez, stateSource, RezzedFrom);
         if (itemToQueue.Action != LUType.Unknown)
             ItemsToStart.Add(itemToQueue);
     }
     if (ItemsToStart.Count != 0)
         m_scriptEngine.MaintenanceThread.AddScriptChange(ItemsToStart.ToArray(), LoadPriority.FirstStart);
 }
Example #51
0
        public static OSD ObjectPhysicsProperties(ISceneChildEntity[] entities)
        {
            ObjectPhysicsPropertiesMessage message = new ObjectPhysicsPropertiesMessage();
#if (!ISWIN)
            int i = 0;
            foreach (ISceneChildEntity entity in entities)
            {
                if (entity != null) i++;
            }
#else
            int i = entities.Count(entity => entity != null);
#endif

            message.ObjectPhysicsProperties = new Primitive.PhysicsProperties[i];
            i = 0;
#if (!ISWIN)
            foreach (ISceneChildEntity entity in entities)
            {
                if (entity != null)
                {
                    message.ObjectPhysicsProperties[i] = new Primitive.PhysicsProperties
                                                             {
                                                                 Density = entity.Density,
                                                                 Friction = entity.Friction,
                                                                 GravityMultiplier = entity.GravityMultiplier,
                                                                 LocalID = entity.LocalId,
                                                                 PhysicsShapeType =
                                                                     (PhysicsShapeType) entity.PhysicsType,
                                                                 Restitution = entity.Restitution
                                                             };
                    i++;
                }
            }
#else
            foreach (ISceneChildEntity entity in entities.Where(entity => entity != null))
            {
                message.ObjectPhysicsProperties[i] = new Primitive.PhysicsProperties
                                                         {
                                                             Density = entity.Density,
                                                             Friction = entity.Friction,
                                                             GravityMultiplier = entity.GravityMultiplier,
                                                             LocalID = entity.LocalId,
                                                             PhysicsShapeType = (PhysicsShapeType) entity.PhysicsType,
                                                             Restitution = entity.Restitution
                                                         };
                i++;
            }
#endif

            OSDMap m = new OSDMap {{"message", OSD.FromString("ObjectPhysicsProperties")}};
            OSD message_body = message.Serialize();
            m.Add("body", message_body);
            return m;
        }
Example #52
0
        public bool Check()
        {
            bool needToContinue = false;

            foreach (IHttpRequestModule iHttpReq in m_modules)
            {
                IServiceRequest httpInfo = null;

                if (iHttpReq != null)
                {
                    httpInfo = iHttpReq.GetNextCompletedRequest();
                    if (!needToContinue)
                    {
                        needToContinue = iHttpReq.GetRequestCount() > 0;
                    }
                }

                if (httpInfo == null)
                {
                    continue;
                }

                while (httpInfo != null)
                {
                    IHttpRequestClass info = (IHttpRequestClass)httpInfo;
                    //MainConsole.Instance.Debug("[AsyncLSL]:" + httpInfo.response_body + httpInfo.status);

                    // Deliver data to prim's remote_data handler

                    iHttpReq.RemoveCompletedRequest(info);

                    object[] resobj = new object[]
                    {
                        new LSL_Types.LSLString(info.ReqID.ToString()),
                        new LSL_Types.LSLInteger(info.Status),
                        new LSL_Types.list(info.Metadata),
                        new LSL_Types.LSLString(info.ResponseBody)
                    };

                    m_ScriptEngine.AddToObjectQueue(info.PrimID, "http_response", new DetectParams[0], resobj);
                    if (info.Status == (int)499 && //Too many for this prim
                        info.VerbroseThrottle)
                    {
                        ISceneChildEntity part = m_ScriptEngine.Scene.GetSceneObjectPart(info.PrimID);
                        if (part != null)
                        {
                            IChatModule chatModule = m_ScriptEngine.Scene.RequestModuleInterface <IChatModule>();
                            if (chatModule != null)
                            {
                                chatModule.SimChat(
                                    part.Name + "(" + part.AbsolutePosition +
                                    ") http_response error: Too many outgoing requests.", ChatTypeEnum.DebugChannel,
                                    2147483647, part.AbsolutePosition, part.Name, part.UUID, false, m_ScriptEngine.Scene);
                            }
                        }
                    }
                    httpInfo = iHttpReq.GetNextCompletedRequest();
                }
            }
            return(needToContinue);
        }
Example #53
0
        public void touch_end (ISceneChildEntity part, ISceneChildEntity child, IClientAPI remoteClient,
                              SurfaceTouchEventArgs surfaceArgs)
        {
            Dictionary<UUID, DetectParams> det = new Dictionary<UUID, DetectParams>();
            if (!CoalescedTouchEvents.TryGetValue(part.LocalId, out det))
                det = new Dictionary<UUID, DetectParams>();

            // Add to queue for all scripts in ObjectID object
            DetectParams detparam = new DetectParams();
            detparam = new DetectParams();
            detparam.Key = remoteClient.AgentId;

            detparam.Populate(m_scriptEngine.findPrimsScene(part.LocalId));
            detparam.LinkNum = child.LinkNum;

            if (surfaceArgs != null)
                detparam.SurfaceTouchArgs = surfaceArgs;

            det[remoteClient.AgentId] = detparam;
            CoalescedTouchEvents[part.LocalId] = det;

            ScriptData[] datas = ScriptEngine.ScriptProtection.GetScripts(part.UUID);

            if (datas == null || datas.Length == 0)
                return; 
            
            string functionName = "touch_end";
            object[] param = new Object[] { new LSL_Types.LSLInteger (det.Count) };

            foreach (ScriptData ID in datas)
            {
                if (CheckIfEventShouldFire(ID, functionName, param))
                    m_scriptEngine.AddToScriptQueue(ID, functionName, new List<DetectParams>(det.Values).ToArray(), EventPriority.FirstStart, param);
            }
            //Remove us from the det param list
            det.Remove(remoteClient.AgentId);
            CoalescedTouchEvents[part.LocalId] = det;
        }
            public void RegisterControlEventsToScript(int controls, int accept, int pass_on, ISceneChildEntity part,
                                                      UUID Script_item_UUID)
            {
                ScriptControllers obj = new ScriptControllers
                {
                    ignoreControls = ScriptControlled.CONTROL_ZERO,
                    eventControls  = ScriptControlled.CONTROL_ZERO,
                    itemID         = Script_item_UUID,
                    part           = part
                };

                if (pass_on == 0 && accept == 0)
                {
                    IgnoredControls   |= (ScriptControlled)controls;
                    obj.ignoreControls = (ScriptControlled)controls;
                }

                if (pass_on == 0 && accept == 1)
                {
                    IgnoredControls   |= (ScriptControlled)controls;
                    obj.ignoreControls = (ScriptControlled)controls;
                    obj.eventControls  = (ScriptControlled)controls;
                }
                if (pass_on == 1 && accept == 1)
                {
                    IgnoredControls    = ScriptControlled.CONTROL_ZERO;
                    obj.eventControls  = (ScriptControlled)controls;
                    obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
                }

                lock (scriptedcontrols)
                {
                    if (pass_on == 1 && accept == 0)
                    {
                        IgnoredControls &= ~(ScriptControlled)controls;
                        if (scriptedcontrols.ContainsKey(Script_item_UUID))
                        {
                            scriptedcontrols.Remove(Script_item_UUID);
                        }
                    }
                    else
                    {
                        scriptedcontrols[Script_item_UUID] = obj;
                    }
                }
                m_sp.ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
            }
Example #55
0
        public void land_collision_end (ISceneChildEntity part, ColliderArgs col)
        {
            List<DetectParams> det = new List<DetectParams>();

            foreach (DetectedObject detobj in col.Colliders)
            {
                DetectParams d = new DetectParams();
                d.Position = new LSL_Types.Vector3(detobj.posVector.X,
                    detobj.posVector.Y,
                    detobj.posVector.Z);
                d.Key = detobj.keyUUID;
                d.Populate(part.ParentEntity.Scene);
                d.LinkNum = part.LinkNum;
                det.Add(d);
            }
            if (det.Count != 0)
            {
                ScriptData[] datas = ScriptEngine.ScriptProtection.GetScripts(part.UUID);

                if (datas == null || datas.Length == 0)
                {
                    //datas = ScriptEngine.ScriptProtection.GetScripts(part.ParentGroup.RootPart.UUID);
                    //if (datas == null || datas.Length == 0)
                        return;
                }
                string functionName = "land_collision_end";
                object[] param = new Object[] { new LSL_Types.Vector3(det[0].Position) };

                foreach (ScriptData ID in datas)
                {
                    if (CheckIfEventShouldFire(ID, functionName, param))
                        m_scriptEngine.AddToScriptQueue(ID, functionName, det.ToArray(), EventPriority.FirstStart, param);
                }
            }
        }
Example #56
0
        private int m_MaxEmailSize           = 4096; // largest email allowed by default, as per lsl docs.

        #region IEmailModule Members

        /// <summary>
        ///     SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="scene">Can be null</param>
        public void SendEmail(UUID objectID, string address, string subject, string body, IScene scene)
        {
            //Check if address is empty
            if (address == string.Empty)
            {
                return;
            }

            //FIXED:Check the email is correct form in REGEX
            const string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                              + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                              + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                              + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                              + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict      = new Regex(EMailpatternStrict);
            bool  isEMailStrictMatch = EMailreStrict.IsMatch(address);

            if (!isEMailStrictMatch)
            {
                MainConsole.Instance.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > m_MaxEmailSize)
            {
                MainConsole.Instance.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
                return;
            }

            string LastObjectName       = string.Empty;
            string LastObjectPosition   = string.Empty;
            string LastObjectRegionName = string.Empty;

            if (scene != null)
            {
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition,
                                              out LastObjectRegionName, scene);
            }

            if (!address.EndsWith(m_InterObjectHostname))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // regular email, send it out
                    try
                    {
                        //Creation EmailMessage

                        string fromEmailAddress;

                        if (scene != null && objectID != UUID.Zero)
                        {
                            fromEmailAddress = objectID.ToString() + "@" + m_HostName;
                        }
                        else
                        {
                            fromEmailAddress = "no-reply@" + m_HostName;
                        }

                        EmailMessage emailMessage = new EmailMessage
                        {
                            FromAddress =
                                new EmailAddress(fromEmailAddress),
                            Subject = subject
                        };

                        //To - Only One
                        emailMessage.AddToAddress(new EmailAddress(address));
                        //Text
                        emailMessage.BodyText = body;
                        if (scene != null)
                        {
                            // If Object Null Dont Include Object Info Headers (Offline IMs)
                            if (objectID != UUID.Zero)
                            {
                                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                                        "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                        LastObjectPosition + "\n\n";
                            }

                            emailMessage.BodyText += emailMessage.BodyText;
                        }



                        //Config SMTP Server
                        //Set SMTP SERVER config
                        SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                        // Add authentication only when requested
                        if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                        {
                            smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                        }
                        //Add timeout of 15 seconds
                        smtpServer.ServerTimeout = 15000;
                        //Send Email Message
                        didError = !emailMessage.Send(smtpServer);

                        //Log
                        if (!didError)
                        {
                            MainConsole.Instance.Info("[EMAIL] EMail sent to: " + address + " from object: " +
                                                      fromEmailAddress);
                        }
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                        didError = true;
                    }
                }
                if (((didError) || (m_localOnly)) && (scene != null))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName, scene);
                    if (part != null)
                    {
                        IScenePresence sp = scene.GetScenePresence(part.OwnerID);
                        if ((sp != null) && (!sp.IsChildAgent))
                        {
                            sp.ControllingClient.SendAlertMessage(
                                "llEmail: email module not configured for outgoing emails");
                        }
                    }
                }
            }
            else
            {
                // inter object email, keep it in the family
                string guid = address.Substring(0, address.IndexOf("@", StringComparison.Ordinal));
                UUID   toID = new UUID(guid);

                if (IsLocal(toID, scene))
                {
                    // object in this region
                    InsertEmail(toID, new Email
                    {
                        time =
                            ((int)
                             ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds))
                            .
                            ToString(CultureInfo.InvariantCulture),
                        subject = subject,
                        sender  = objectID.ToString() + "@" + m_InterObjectHostname,
                        message = "Object-Name: " + LastObjectName +
                                  "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                  LastObjectPosition + "\n\n" + body,
                        toPrimID = toID
                    });
                }
                else
                {
                    // object on another region

                    Email email = new Email
                    {
                        time =
                            ((int)
                             ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                            ToString(CultureInfo.InvariantCulture),
                        subject  = subject,
                        sender   = objectID.ToString() + "@" + m_InterObjectHostname,
                        message  = body,
                        toPrimID = toID
                    };
                    IEmailConnector conn = Framework.Utilities.DataManager.RequestPlugin <IEmailConnector>();
                    conn.InsertEmail(email);
                }
            }
        }
Example #57
0
        public void moving_end (ISceneChildEntity part)
        {
            ScriptData[] datas = ScriptEngine.ScriptProtection.GetScripts(part.UUID);

            if (datas == null || datas.Length == 0)
            {
                datas = ScriptEngine.ScriptProtection.GetScripts(part.ParentEntity.RootChild.UUID);
                if (datas == null || datas.Length == 0)
                    return;
            }
            string functionName = "moving_end";
            object[] param = new object[0];

            foreach (ScriptData ID in datas)
            {
                if (CheckIfEventShouldFire(ID, functionName, param))
                    m_scriptEngine.AddToScriptQueue(ID, functionName, new DetectParams[0], EventPriority.FirstStart, param);
            }
        }
Example #58
0
        public void GodlikeMessage(IClientAPI client, UUID requester, string Method, List <string> Parameters)
        {
            if (RegionConnector == null)
            {
                return;
            }
            IScenePresence Sp = client.Scene.GetScenePresence(client.AgentId);

            if (!client.Scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
            {
                return;
            }

            string parameter1 = Parameters[0];

            if (Method == "telehub")
            {
                if (parameter1 == "spawnpoint remove")
                {
                    Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID,
                                                                  client.Scene.RegionInfo.RegionHandle);
                    if (telehub == null)
                    {
                        return;
                    }
                    //Remove the one we sent at X
                    telehub.SpawnPos.RemoveAt(int.Parse(Parameters[1]));
                    RegionConnector.AddTelehub(telehub, client.Scene.RegionInfo.RegionHandle);
                    client.Scene.RegionInfo.RegionSettings.TeleHub = telehub;

                    SendTelehubInfo(client);
                }
                if (parameter1 == "spawnpoint add")
                {
                    ISceneChildEntity part = Sp.Scene.GetSceneObjectPart(uint.Parse(Parameters[1]));
                    if (part == null)
                    {
                        return;
                    }
                    Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID,
                                                                  client.Scene.RegionInfo.RegionHandle);
                    if (telehub == null)
                    {
                        return;
                    }
                    telehub.RegionLocX = client.Scene.RegionInfo.RegionLocX;
                    telehub.RegionLocY = client.Scene.RegionInfo.RegionLocY;
                    telehub.RegionID   = client.Scene.RegionInfo.RegionID;
                    Vector3 pos = new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ);
                    if (telehub.TelehubLocX == 0 && telehub.TelehubLocY == 0)
                    {
                        return;                                        //No spawns without a telehub
                    }
                    telehub.SpawnPos.Add(part.AbsolutePosition - pos); //Spawns are offsets
                    RegionConnector.AddTelehub(telehub, client.Scene.RegionInfo.RegionHandle);
                    client.Scene.RegionInfo.RegionSettings.TeleHub = telehub;

                    SendTelehubInfo(client);
                }
                if (parameter1 == "delete")
                {
                    RegionConnector.RemoveTelehub(client.Scene.RegionInfo.RegionID, client.Scene.RegionInfo.RegionHandle);
                    client.Scene.RegionInfo.RegionSettings.TeleHub = new Telehub();

                    SendTelehubInfo(client);
                }
                if (parameter1 == "connect")
                {
                    ISceneChildEntity part = Sp.Scene.GetSceneObjectPart(uint.Parse(Parameters[1]));
                    if (part == null)
                    {
                        return;
                    }
                    Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID,
                                                                  client.Scene.RegionInfo.RegionHandle);
                    if (telehub == null)
                    {
                        telehub = new Telehub();
                    }
                    telehub.RegionLocX  = client.Scene.RegionInfo.RegionLocX;
                    telehub.RegionLocY  = client.Scene.RegionInfo.RegionLocY;
                    telehub.RegionID    = client.Scene.RegionInfo.RegionID;
                    telehub.TelehubLocX = part.AbsolutePosition.X;
                    telehub.TelehubLocY = part.AbsolutePosition.Y;
                    telehub.TelehubLocZ = part.AbsolutePosition.Z;
                    telehub.TelehubRotX = part.ParentEntity.Rotation.X;
                    telehub.TelehubRotY = part.ParentEntity.Rotation.Y;
                    telehub.TelehubRotZ = part.ParentEntity.Rotation.Z;
                    telehub.ObjectUUID  = part.UUID;
                    telehub.Name        = part.Name;
                    RegionConnector.AddTelehub(telehub, client.Scene.RegionInfo.RegionHandle);
                    client.Scene.RegionInfo.RegionSettings.TeleHub = telehub;

                    SendTelehubInfo(client);
                }

                if (parameter1 == "info ui")
                {
                    SendTelehubInfo(client);
                }
            }
        }
Example #59
0
 public SOPObjectMaterial(int m_face, ISceneChildEntity m_parent)
 {
     this.m_face = m_face;
     this.m_parent = m_parent;
 }
        /// <summary>
        ///     This method scans over the objects which registered an interest in listen callbacks.
        ///     For everyone it finds, it checks if it fits the given filter. If it does,  then
        ///     enqueue the message for delivery to the objects listen event handler.
        ///     The enqueued ListenerInfo no longer has filter values, but the actually trigged values.
        ///     Objects that do an llSay have their messages delivered here and for nearby avatars,
        ///     the OnChatFromClient event is used.
        /// </summary>
        /// <param name="type">type of delivery (whisper,say,shout or regionwide)</param>
        /// <param name="channel">channel to sent on</param>
        /// <param name="name">name of sender (object or avatar)</param>
        /// <param name="fromID">key of sender (object or avatar)</param>
        /// <param name="msg">msg to sent</param>
        /// <param name="position"></param>
        /// <param name="range"></param>
        /// <param name="toID"></param>
        public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID fromID, string msg,
                                   Vector3 position,
                                   float range, UUID toID)
        {
            //Make sure that the cmd handler thread is running
            m_scriptModule.PokeThreads(UUID.Zero);
            if (BlockedChannels.Contains(channel))
            {
                return;
            }
            // MainConsole.Instance.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}",
            //                   type, channel, name, id, msg);

            // Determine which listen event filters match the given set of arguments, this results
            // in a limited set of listeners, each belonging a host. If the host is in range, add them
            // to the pending queue.
            foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, fromID, msg))
            {
                // Dont process if this message is from yourself!
                if (li.GetHostID().Equals(fromID))
                {
                    continue;
                }

                ISceneChildEntity sPart = m_scene.GetSceneObjectPart(li.GetHostID());
                if (sPart == null)
                {
                    continue;
                }

                if (toID != UUID.Zero)
                {
                    if (sPart.UUID != toID &&
                        sPart.AttachedAvatar != toID)
                    {
                        continue;
                    }
                }
                //Only allow the message to go on if it is an attachment with the given avatars ID or the part ID is right

                double dis = Util.GetDistanceTo(sPart.AbsolutePosition, position);
                switch (type)
                {
                case ChatTypeEnum.Whisper:
                    if (dis < m_whisperdistance)
                    {
                        QueueMessage(new ListenerInfo(li, name, fromID, msg));
                    }
                    break;

                case ChatTypeEnum.Say:
                    if (dis < m_saydistance)
                    {
                        QueueMessage(new ListenerInfo(li, name, fromID, msg));
                    }
                    break;

                case ChatTypeEnum.ObsoleteSay:
                    if (dis < m_saydistance)
                    {
                        QueueMessage(new ListenerInfo(li, name, fromID, msg));
                    }
                    break;

                case ChatTypeEnum.Shout:
                    if (dis < m_shoutdistance)
                    {
                        QueueMessage(new ListenerInfo(li, name, fromID, msg));
                    }
                    break;

                case ChatTypeEnum.Custom:
                    if (dis < range)
                    {
                        QueueMessage(new ListenerInfo(li, name, fromID, msg));
                    }
                    break;

                case ChatTypeEnum.Region:
                    QueueMessage(new ListenerInfo(li, name, fromID, msg));
                    break;
                }
            }
        }