void OnMakeRootAgent (IScenePresence presence) { if ((presence.CallbackURI != null) && !presence.CallbackURI.Equals("")) { WebUtils.ServiceOSDRequest(presence.CallbackURI, null, "DELETE", 10000, false, false); presence.CallbackURI = null; ICapsService service = m_scene.RequestModuleInterface<ICapsService>(); if (service != null) { IClientCapsService clientCaps = service.GetClientCapsService (presence.UUID); if (clientCaps != null) { IRegionClientCapsService regionCaps = clientCaps.GetCapsService (m_scene.RegionInfo.RegionHandle); if (regionCaps != null) { regionCaps.RootAgent = true; foreach (IRegionClientCapsService regionClientCaps in clientCaps.GetCapsServices ()) { if (regionCaps.RegionHandle != regionClientCaps.RegionHandle) regionClientCaps.RootAgent = false; //Reset any other agents that we might have } } } } } }
public bool CanCreateAt(IScenePresence presence, Vector3 location) { if (m_parcels == null) return true; SceneParcel parcel; if (m_parcels.TryGetParcel(location, out parcel)) { // If we can't enter the parcel we can't create anything there either if (!CanEnterParcel(presence, parcel)) return false; // CreateObjects flag set? We're good if ((parcel.Flags & ParcelFlags.CreateObjects) == ParcelFlags.CreateObjects) return true; // CreateGroupObjects flag set and we're a member of the parcel group? We're good if ((parcel.Flags & ParcelFlags.CreateGroupObjects) == ParcelFlags.CreateGroupObjects && IsInGroup(presence, parcel.GroupID)) return true; return false; } else { m_log.Warn("No parcel found at " + location); return true; } }
void OnMakeRootAgent (IScenePresence presence) { if ((presence.CallbackURI != null) && !presence.CallbackURI.Equals("")) { WebUtils.ServiceOSDRequest(presence.CallbackURI, null, "DELETE", 10000); presence.CallbackURI = null; } }
private void EventManager_OnNewPresence(IScenePresence presence) { if (_OnNewUser != null) { NewUserEventArgs e = new NewUserEventArgs { Avatar = new SPAvatar(m_internalScene, presence.UUID, m_security) }; _OnNewUser(this, e); } }
void EventManager_OnRemovePresence (IScenePresence presence) { ScriptControllerPresenceModule m = (ScriptControllerPresenceModule)presence.RequestModuleInterface<IScriptControllerModule> (); if (m != null) { m.Close (); presence.UnregisterModuleInterface<IScriptControllerModule> (m); } }
public Animator (IScenePresence sp) { m_scenePresence = sp; IConfig animationConfig = sp.Scene.Config.Configs ["Animations"]; if (animationConfig != null) { SLOWFLY_DELAY = animationConfig.GetInt ("SlowFlyDelay", SLOWFLY_DELAY); m_useSplatAnimation = animationConfig.GetBoolean ("enableSplatAnimation", m_useSplatAnimation); } //This step makes sure that we don't waste almost 2.5! seconds on incoming agents m_animations = new AnimationSet (DefaultAnimations); }
void OnMakeRootAgent(IScenePresence presence) { try { //Add the user FileStream stream = new FileStream(m_fileName, FileMode.OpenOrCreate); StreamWriter m_streamWriter = new StreamWriter(stream); m_streamWriter.BaseStream.Position += m_streamWriter.BaseStream.Length; string LineToWrite = DateTime.Now.ToLongTimeString() + " - " + presence.Name + " entered " + presence.Scene.RegionInfo.RegionName + "."; m_timesOfUsers[presence.UUID] = DateTime.Now; m_streamWriter.WriteLine(LineToWrite); m_streamWriter.WriteLine(); m_streamWriter.Close(); } catch { } }
public bool ShowEntityToClient(IScenePresence client, IEntity entity, IScene scene, int currentTickCount) { if (!m_useCulling) return true; //If we arn't using culling, return true by default to show all prims if (entity == null || client == null || scene == null) return false; bool cull = false; lock (m_previousCulled) { if (m_previousCulled.TryGetValue(entity.LocalId, out cull)) { Int32 diff = currentTickCount - m_lastCached; Int32 timingDiff = (diff >= 0) ? diff : (diff + Util.EnvironmentTickCountMask + 1); if (timingDiff > 5*1000) //Only recheck every 5 seconds { m_lastCached = Util.EnvironmentTickCount(); m_previousCulled.Clear(); } else return cull; } } if (m_useDistanceCulling && !DistanceCulling(client, entity, scene)) { lock (m_previousCulled) m_previousCulled[entity.LocalId] = false; return false; } if (!ParcelPrivateCulling(client, entity)) { lock (m_previousCulled) m_previousCulled[entity.LocalId] = false; return false; } //No more, guess its fine lock (m_previousCulled) m_previousCulled[entity.LocalId] = true; return true; }
/// <summary> /// The default prioritizer for interest list events. Returns the /// squared distance between the event and the target presence /// </summary> public static double?DefaultPrioritizer(InterestListEvent eventData, IScenePresence presence) { // A simple distance-based prioritizer return(Vector3.DistanceSquared(presence.ScenePosition, eventData.ScenePosition)); }
public void Close() { m_sp.Scene.EventManager.OnMakeChildAgent -= EventManager_OnMakeChildAgent; m_sp.ControllingClient.OnForceReleaseControls -= HandleForceReleaseControls; m_sp = null; }
/// <summary> /// Handle an alert command from the console. /// </summary> /// <param name="cmdparams"></param> protected void HandleAlertConsoleCommand(IScene scene, string [] cmdparams) { string message = ""; string userName = ""; string cmdType = cmdparams [1].ToLower(); if (cmdType.StartsWith("g", StringComparison.Ordinal) || cmdType.StartsWith("b", StringComparison.Ordinal)) { // general if (cmdparams.Length > 2) { message = Util.CombineParams(cmdparams, 2); } else { message = MainConsole.Instance.Prompt("Message to send?", ""); } if (message == "") { return; } if (cmdType.StartsWith("g", StringComparison.Ordinal)) { MainConsole.Instance.InfoFormat("[DIALOG]: Sending general alert in region {0} with message '{1}'", scene.RegionInfo.RegionName, message); // send the message scene.ForEachScenePresence(delegate(IScenePresence sp) { if (!sp.IsChildAgent) { sp.ControllingClient.SendAlertMessage(message); } }); } else { MainConsole.Instance.InfoFormat("[DIALOG]: Sending broadcast alert to all regions with message '{0}'", message); // broadcast the message foreach (IScene scn in MainConsole.Instance.ConsoleScenes) { scn.ForEachScenePresence(delegate(IScenePresence sp) { if (!sp.IsChildAgent) { sp.ControllingClient.SendAlertMessage(message); } }); } } return; } // user alert if (cmdparams.Length >= 4) { userName = cmdparams [2] + " " + cmdparams [3]; } else { userName = MainConsole.Instance.Prompt("User name? (First Last)", ""); } if (userName == "") { return; } if (cmdparams.Length > 4) { message = Util.CombineParams(cmdparams, 4); } else { message = MainConsole.Instance.Prompt("Message to send?", ""); } if (message == "") { return; } MainConsole.Instance.InfoFormat("[DIALOG]: Sending alert in region {0} to {1} with message '{2}'", scene.RegionInfo.RegionName, userName, message); // send the message to the user IScenePresence spc = scene.SceneGraph.GetScenePresence(userName); if (spc != null && !spc.IsChildAgent) { spc.ControllingClient.SendAgentAlertMessage(message, false); } }
public void RemoveAvatarFromView(IScenePresence sp) { lock (m_lastPresencesInViewLock) lastPresencesDInView.Remove(sp.UUID); }
/// <summary> /// This starts the script and sets up the variables. /// </summary> /// <returns></returns> public bool Start(LUStruct startInfo) { bool reupload = startInfo.Action == LUType.Reupload; DateTime StartTime = DateTime.Now.ToUniversalTime(); Running = true; Suspended = false; //Clear out the removing of events for this script. IgnoreNew = false; Interlocked.Increment(ref VersionID); //Reset this StartedFromSavedState = false; //Clear out previous errors if they were not cleaned up m_ScriptEngine.ScriptErrorReporter.RemoveError(ItemID); //Find the inventory item Part.TaskInventory.TryGetValue(ItemID, out InventoryItem); if (InventoryItem == null) { MainConsole.Instance.Warn("[VS]: Could not find inventory item for script " + ItemID + ", part" + Part.Name + "@" + Part.AbsolutePosition); return(false); } //Try to see if this was rezzed from someone's inventory UserInventoryItemID = Part.FromUserInventoryItemID; //Try to find the avatar who started this. IScenePresence presence = World.GetScenePresence(Part.OwnerID); if (startInfo.ClearStateSaves) { m_ScriptEngine.StateSave.DeleteFrom(this); } //Now that the initial loading is complete, // we need to find the state save and start loading the info from it StateSave LastStateSave = m_ScriptEngine.StateSave.FindScriptStateSave(this); if (!reupload && Loading && LastStateSave != null) { //Deserialize the most important pieces first Source = LastStateSave.Source; } if (string.IsNullOrEmpty(Source)) { byte[] asset = Part.ParentEntity.Scene.AssetService.GetData(InventoryItem.AssetID.ToString()); if (null == asset) { MainConsole.Instance.ErrorFormat( "[ScriptData]: " + "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", InventoryItem.Name, InventoryItem.ItemID, Part.AbsolutePosition, Part.ParentEntity.Scene.RegionInfo.RegionName, InventoryItem.AssetID); ScriptEngine.ScriptProtection.RemoveScript(this); return(false); } Source = Utils.BytesToString(asset); } if (string.IsNullOrEmpty(Source)) { MainConsole.Instance.ErrorFormat( "[ScriptData]: " + "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", InventoryItem.Name, InventoryItem.ItemID, Part.AbsolutePosition, Part.ParentEntity.Scene.RegionInfo.RegionName, InventoryItem.AssetID); ScriptEngine.ScriptProtection.RemoveScript(this); return(false); } #region HTML Reader if (ScriptEngine.ScriptProtection.AllowHTMLLinking) { //Read the URL and load it. if (Source.Contains("#IncludeHTML ")) { string URL = ""; int line = Source.IndexOf("#IncludeHTML "); URL = Source.Remove(0, line); URL = URL.Replace("#IncludeHTML ", ""); URL = URL.Split('\n')[0]; string webSite = Utilities.ReadExternalWebsite(URL); Source = Source.Replace("#IncludeHTML " + URL, webSite); } } else { //Remove the line then if (Source.Contains("#IncludeHTML ")) { string URL = ""; int line = Source.IndexOf("#IncludeHTML "); URL = Source.Remove(0, line); URL = URL.Replace("#IncludeHTML ", ""); URL = URL.Split('\n')[0]; Source = Source.Replace("#IncludeHTML " + URL, ""); } } #endregion //Find the default state save DefaultState = m_ScriptEngine.Compiler.FindDefaultStateForScript(Source); State = DefaultState; //If the saved state exists, if it isn't a reupload (something changed), and if the assembly exists, load the state save if (!reupload && Loading && LastStateSave != null && File.Exists(LastStateSave.AssemblyName)) { //Retrive the previous assembly AssemblyName = LastStateSave.AssemblyName; } else { Compiled = false; //if (!reupload && Loading && LastStateSave != null && !LastStateSave.Compiled) // return false;//If we're trying to start up and we failed before, just give up if (reupload) { LastStateSave = null; //Close the previous script CloseAndDispose(false); //We don't want to back it up Interlocked.Increment(ref VersionID); m_ScriptEngine.MaintenanceThread.SetEventSchSetIgnoreNew(this, false); // accept new events } //Try to find a previously compiled script in this instance string PreviouslyCompiledAssemblyName = ScriptEngine.ScriptProtection.TryGetPreviouslyCompiledScript(Source); if (PreviouslyCompiledAssemblyName != null) { //Already exists in this instance, so we do not need to check whether it exists AssemblyName = PreviouslyCompiledAssemblyName; } else { try { m_ScriptEngine.Compiler.PerformScriptCompile(Source, Part.OwnerID, out AssemblyName); #region Errors and Warnings #region Errors string[] compileerrors = m_ScriptEngine.Compiler.GetErrors(); if (compileerrors.Length != 0) { string error = string.Empty; foreach (string compileerror in compileerrors) { error += compileerror; } DisplayUserNotification(error, "compiling", reupload, true); //It might have failed, but we still need to add it so that we can reuse this script data class later ScriptEngine.ScriptProtection.AddNewScript(this); m_ScriptEngine.StateSave.SaveStateTo(this, true); return(false); } #endregion #region Warnings if (m_ScriptEngine.ShowWarnings) { string[] compilewarnings = m_ScriptEngine.Compiler.GetWarnings(); if (compilewarnings != null && compilewarnings.Length != 0) { string error = string.Empty; foreach (string compileerror in compilewarnings) { error += compileerror; } DisplayUserNotification(error, "compiling", reupload, false); //It might have failed, but we still need to add it so that we can reuse this script data class later ScriptEngine.ScriptProtection.AddNewScript(this); return(false); } } #endregion #endregion } catch (Exception ex) { //LEAVE IT AS ToString() SO THAT WE GET THE STACK TRACE TOO DisplayUserNotification(ex.ToString(), "(exception) compiling", reupload, true); //It might have failed, but we still need to add it so that we can reuse this script data class later ScriptEngine.ScriptProtection.AddNewScript(this); return(false); } } } bool useDebug = false; if (useDebug) { MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Stage 1 compile: " + (DateTime.Now.ToUniversalTime() - StartTime).TotalSeconds); } //Create the app domain if needed. try { Script = m_ScriptEngine.AppDomainManager.LoadScript(AssemblyName, "Script.ScriptClass", out AppDomain); m_ScriptEngine.Compiler.FinishCompile(this, Script); //Add now so that we don't add it too early and give it the possibility to fail ScriptEngine.ScriptProtection.AddPreviouslyCompiled(Source, this); } catch (FileNotFoundException) // Not valid!!! { MainConsole.Instance.Error("[" + m_ScriptEngine.ScriptEngineName + "]: File not found in app domain creation. Corrupt state save! " + AssemblyName); ScriptEngine.ScriptProtection.RemovePreviouslyCompiled(Source); return(Start(startInfo)); // Lets restart the script if this happens } catch (Exception ex) { DisplayUserNotification(ex.ToString(), "app domain creation", reupload, true); //It might have failed, but we still need to add it so that we can reuse this script data class later ScriptEngine.ScriptProtection.AddNewScript(this); return(false); } Compiled = true; //We compiled successfully //ILease lease = (ILease)RemotingServices.GetLifetimeService(Script as MarshalByRefObject); //if (lease != null) //Its null if it is all running in the same app domain // lease.Register(Script.Sponsor); //If its a reupload, an avatar is waiting for the script errors if (reupload) { m_ScriptEngine.ScriptErrorReporter.AddError(ItemID, new ArrayList(new[] { "SUCCESSFULL" })); } if (useDebug) { MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Stage 2 compile: " + (DateTime.Now.ToUniversalTime() - StartTime).TotalSeconds); } SetApis(); //Now do the full state save finding now that we have an app domain. if (LastStateSave != null) { string assy = AssemblyName; // don't restore the assembly name, the one we have is right (if re-compiled or not) m_ScriptEngine.StateSave.Deserialize(this, LastStateSave); AssemblyName = assy; if (string.IsNullOrEmpty(this.State) && DefaultState != this.State) //Sometimes, "" is a valid state for other script languages { MainConsole.Instance.Warn("Resetting broken script save state\n" + " : " + InventoryItem.Name + ":" + this.Part.Name + " @ " + Part.AbsolutePosition + "\n in region " + Part.ParentEntity.Scene.RegionInfo.RegionName); this.State = DefaultState; m_ScriptEngine.StateSave.DeleteFrom(Part, LastStateSave.ItemID); m_ScriptEngine.StateSave.SaveStateTo(this, true); } else { // we get new rez events on sim restart, too // but if there is state, then we fire the change // event StartedFromSavedState = true; } // ItemID changes sometimes (not sure why, but observed it) // If so we want to clear out the old save state, // which would otherwise have hung around in the object forever if (LastStateSave.ItemID != ItemID) { m_ScriptEngine.StateSave.DeleteFrom(Part, LastStateSave.ItemID); m_ScriptEngine.StateSave.SaveStateTo(this, true); } } else { //Make a new state save now m_ScriptEngine.StateSave.SaveStateTo(this, true); } //Set the event flags Part.SetScriptEvents(ItemID, Script.GetStateEventFlags(State)); // Add it to our script memstruct so it can be found by other scripts ScriptEngine.ScriptProtection.AddNewScript(this); //All done, compiled successfully Loading = false; if (MainConsole.Instance.IsDebugEnabled) { TimeSpan time = (DateTime.Now.ToUniversalTime() - StartTime); MainConsole.Instance.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Started Script " + InventoryItem.Name + " in object " + Part.Name + "@" + Part.ParentEntity.RootChild.AbsolutePosition + (presence != null ? " by " + presence.Name : "") + " in region " + Part.ParentEntity.Scene.RegionInfo.RegionName + " in " + time.TotalSeconds + " seconds."); } return(true); }
public void TriggerOnRemovePresence (IScenePresence presence) { OnNewPresenceDelegate handlerRemovePresence = OnRemovePresence; if (handlerRemovePresence != null) { foreach (OnNewPresenceDelegate d in handlerRemovePresence.GetInvocationList ()) { try { d (presence); } catch (Exception e) { m_log.ErrorFormat ( "[EVENT MANAGER]: Delegate for TriggerOnRemovePresence failed - continuing. {0} {1}", e.ToString (), e.StackTrace); } } } }
protected void SendTerrainUpdatesForClient(IScenePresence presence) { if (!m_sendTerrainUpdatesByViewDistance || m_noTerrain || presence.DrawDistance == 0) return; if (presence == null) return; bool[,] terrainarray; lock (m_terrainPatchesSent) { m_terrainPatchesSent.TryGetValue(presence.UUID, out terrainarray); } bool fillLater = false; if (terrainarray == null) { int xSize = m_scene.RegionInfo.RegionSizeX != int.MaxValue ? m_scene.RegionInfo.RegionSizeX/Constants.TerrainPatchSize : Constants.RegionSize/Constants.TerrainPatchSize; int ySize = m_scene.RegionInfo.RegionSizeX != int.MaxValue ? m_scene.RegionInfo.RegionSizeY/Constants.TerrainPatchSize : Constants.RegionSize/Constants.TerrainPatchSize; terrainarray = new bool[xSize,ySize]; fillLater = true; } List<int> xs = new List<int>(); List<int> ys = new List<int>(); int startX = (((int) (presence.AbsolutePosition.X - presence.DrawDistance))/Constants.TerrainPatchSize) - 2; startX = Math.Max(startX, 0); startX = Math.Min(startX, m_scene.RegionInfo.RegionSizeX/Constants.TerrainPatchSize); int startY = (((int) (presence.AbsolutePosition.Y - presence.DrawDistance))/Constants.TerrainPatchSize) - 2; startY = Math.Max(startY, 0); startY = Math.Min(startY, m_scene.RegionInfo.RegionSizeY/Constants.TerrainPatchSize); int endX = (((int) (presence.AbsolutePosition.X + presence.DrawDistance))/Constants.TerrainPatchSize) + 2; endX = Math.Max(endX, 0); endX = Math.Min(endX, m_scene.RegionInfo.RegionSizeX/Constants.TerrainPatchSize); int endY = (((int) (presence.AbsolutePosition.Y + presence.DrawDistance))/Constants.TerrainPatchSize) + 2; endY = Math.Max(endY, 0); endY = Math.Min(endY, m_scene.RegionInfo.RegionSizeY/Constants.TerrainPatchSize); for (int x = startX; x < endX; x++) { for (int y = startY; y < endY; y++) { if (x < 0 || y < 0 || x >= m_scene.RegionInfo.RegionSizeX/Constants.TerrainPatchSize || y >= m_scene.RegionInfo.RegionSizeY/Constants.TerrainPatchSize) continue; //Need to make sure we don't send the same ones over and over if (!terrainarray[x, y]) { Vector3 posToCheckFrom = new Vector3(presence.AbsolutePosition.X % m_scene.RegionInfo.RegionSizeX, presence.AbsolutePosition.Y % m_scene.RegionInfo.RegionSizeY, presence.AbsolutePosition.Z); //Check which has less distance, camera or avatar position, both have to be done if (Util.DistanceLessThan(posToCheckFrom, new Vector3( x*Constants.TerrainPatchSize, y*Constants.TerrainPatchSize, 0), presence.DrawDistance + 50) || Util.DistanceLessThan(presence.CameraPosition, new Vector3(x*Constants.TerrainPatchSize, y*Constants.TerrainPatchSize, 0), presence.DrawDistance + 50)) //Its not a radius, its a diameter and we add 35 so that it doesn't look like it cuts off { //They can see it, send it to them terrainarray[x, y] = true; xs.Add(x); ys.Add(y); //Wait and send them all at once //presence.ControllingClient.SendLayerData(x, y, serializedMap); } } } } if (xs.Count != 0) { //Send all the terrain patches at once presence.ControllingClient.SendLayerData(xs.ToArray(), ys.ToArray(), m_channel.GetSerialized(), TerrainPatch.LayerType.Land); if (m_use3DWater) { //Send all the water patches at once presence.ControllingClient.SendLayerData(xs.ToArray(), ys.ToArray(), m_waterChannel.GetSerialized(), TerrainPatch.LayerType.Water); } } if ((xs.Count != 0) || (fillLater)) { if (m_terrainPatchesSent.ContainsKey(presence.UUID)) { lock (m_terrainPatchesSent) m_terrainPatchesSent[presence.UUID] = terrainarray; } else { lock (m_terrainPatchesSent) m_terrainPatchesSent.Add(presence.UUID, terrainarray); } } }
private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { //m_log.InfoFormat("[INVENTORY TRANSFER]: OnInstantMessage {0}", im.dialog); Scene scene = FindClientScene(client.AgentId); if (scene == null) // Something seriously wrong here. { return; } if (im.dialog == (byte)InstantMessageDialog.InventoryOffered) { //m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0])); if (im.binaryBucket.Length < 17) // Invalid { return; } UUID receipientID = new UUID(im.toAgentID); IScenePresence user = scene.GetScenePresence(receipientID); UUID copyID; // First byte is the asset type AssetType assetType = (AssetType)im.binaryBucket[0]; if (AssetType.Folder == assetType) { UUID folderID = new UUID(im.binaryBucket, 1); m_log.DebugFormat("[INVENTORY TRANSFER]: Inserting original folder {0} " + "into agent {1}'s inventory", folderID, new UUID(im.toAgentID)); InventoryFolderBase folderCopy = null; ILLClientInventory inventoryModule = scene.RequestModuleInterface <ILLClientInventory>(); if (inventoryModule != null) { folderCopy = inventoryModule.GiveInventoryFolder(receipientID, client.AgentId, folderID, UUID.Zero); } if (folderCopy == null) { client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false); return; } // The outgoing binary bucket should contain only the byte which signals an asset folder is // being copied and the following bytes for the copied folder's UUID copyID = folderCopy.ID; byte[] copyIDBytes = copyID.GetBytes(); im.binaryBucket = new byte[1 + copyIDBytes.Length]; im.binaryBucket[0] = (byte)AssetType.Folder; Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length); if (user != null) { user.ControllingClient.SendBulkUpdateInventory(folderCopy); } im.imSessionID = folderID.Guid; } else { // First byte of the array is probably the item type // Next 16 bytes are the UUID UUID itemID = new UUID(im.binaryBucket, 1); m_log.DebugFormat("[INVENTORY TRANSFER]: (giving) Inserting item {0} " + "into agent {1}'s inventory", itemID, new UUID(im.toAgentID)); InventoryItemBase itemCopy = null; ILLClientInventory inventoryModule = scene.RequestModuleInterface <ILLClientInventory>(); if (inventoryModule != null) { itemCopy = inventoryModule.GiveInventoryItem( new UUID(im.toAgentID), client.AgentId, itemID, UUID.Zero); } if (itemCopy == null) { client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false); return; } copyID = itemCopy.ID; Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16); if (user != null) { user.ControllingClient.SendBulkUpdateInventory(itemCopy); } im.imSessionID = itemID.Guid; } // Send the IM to the recipient. The item is already // in their inventory, so it will not be lost if // they are offline. // if (user != null) { user.ControllingClient.SendInstantMessage(im); return; } else { if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im, delegate(bool success) { if (!success) { client.SendAlertMessage("User not online. Inventory has been saved"); } }); } } } else if (im.dialog == (byte)InstantMessageDialog.InventoryAccepted) { IScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im, delegate(bool success) {}); } } } else if (im.dialog == (byte)InstantMessageDialog.InventoryDeclined) { // Here, the recipient is local and we can assume that the // inventory is loaded. Courtesy of the above bulk update, // It will have been pushed to the client, too // IInventoryService invService = scene.InventoryService; InventoryFolderBase trashFolder = invService.GetFolderForType(client.AgentId, AssetType.TrashFolder); UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId); item = invService.GetItem(item); InventoryFolderBase folder = null; if (item != null && trashFolder != null) { item.Folder = trashFolder.ID; // Diva comment: can't we just update this item??? List <UUID> uuids = new List <UUID>(); uuids.Add(item.ID); invService.DeleteItems(item.Owner, uuids); ILLClientInventory inventory = client.Scene.RequestModuleInterface <ILLClientInventory>(); if (inventory != null) { inventory.AddInventoryItem(client, item); } } else { folder = new InventoryFolderBase(inventoryID, client.AgentId); folder = invService.GetFolder(folder); if (folder != null & trashFolder != null) { folder.ParentID = trashFolder.ID; invService.MoveFolder(folder); } } if ((null == item && null == folder) | null == trashFolder) { string reason = String.Empty; if (trashFolder == null) { reason += " Trash folder not found."; } if (item == null) { reason += " Item not found."; } if (folder == null) { reason += " Folder not found."; } client.SendAgentAlertMessage("Unable to delete " + "received inventory" + reason, false); } IScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im, delegate(bool success) {}); } } } }
public void OnConnectionClose(IClientAPI client) { IScenePresence sp = null; client.Scene.TryGetScenePresence(client.AgentId, out sp); if (client.IsLoggingOut && sp != null & !sp.IsChildAgent) { MainConsole.Instance.InfoFormat("[ActivityDetector]: Detected logout of user {0} in region {1}", client.Name, client.Scene.RegionInfo.RegionName); //Inform the grid service about it if (m_zombieAgents.Contains(client.AgentId)) { m_zombieAgents.Remove(client.AgentId); return; //They are a known zombie, just clear them out and go on with life! } AgentPosition agentpos = new AgentPosition { AgentID = sp.UUID, AtAxis = sp.CameraAtAxis, Center = sp.CameraPosition, Far = sp.DrawDistance, LeftAxis = Vector3.Zero, Position = sp.AbsolutePosition }; if (agentpos.Position.X > sp.Scene.RegionInfo.RegionSizeX) { agentpos.Position.X = sp.Scene.RegionInfo.RegionSizeX; } if (agentpos.Position.Y > sp.Scene.RegionInfo.RegionSizeY) { agentpos.Position.Y = sp.Scene.RegionInfo.RegionSizeY; } if (agentpos.Position.Z > sp.Scene.RegionInfo.RegionSizeZ) { agentpos.Position.Z = sp.Scene.RegionInfo.RegionSizeZ; } if (agentpos.Position.X < 0) { agentpos.Position.X = 0; } if (agentpos.Position.Y < 0) { agentpos.Position.Y = 0; } if (agentpos.Position.Z < 0) { agentpos.Position.Z = 0; } agentpos.RegionHandle = sp.Scene.RegionInfo.RegionHandle; agentpos.Size = sp.PhysicsActor != null ? sp.PhysicsActor.Size : new Vector3(0, 0, 1.8f); agentpos.UpAxis = Vector3.Zero; agentpos.Velocity = sp.Velocity; agentpos.UserGoingOffline = true; //Don't attempt to add us into other regions //Send the child agent data update ISyncMessagePosterService syncPoster = sp.Scene.RequestModuleInterface <ISyncMessagePosterService>(); if (syncPoster != null) { syncPoster.PostToServer(SyncMessageHelper.AgentLoggedOut(client.AgentId, client.Scene.RegionInfo.RegionID, agentpos)); } } }
void EventManager_OnRemovePresence(IScenePresence presence) { presence.ControllingClient.OnPreSendInstantMessage -= ControllingClient_OnPreSendInstantMessage; }
void EventManager_OnMakeChildAgent(IScenePresence presence, GridRegion destination) { presence.ControllingClient.OnPreSendInstantMessage -= ControllingClient_OnPreSendInstantMessage; }
void EventManager_OnMakeRootAgent(IScenePresence presence) { presence.ControllingClient.OnPreSendInstantMessage += ControllingClient_OnPreSendInstantMessage; }
/// <summary> /// Default constructor /// </summary> /// <param name="presence">The scene presence this interest list belongs to</param> public InterestList(IScenePresence presence, int initialCapacity) { m_presence = presence; m_eventIDs = new Dictionary <UUID, C5.PriorityQueueHandle>(initialCapacity); m_eventHeap = new C5.IntervalHeap <QueuedInterestListEvent>(initialCapacity, m_comparer); }
/// <summary> /// The default sender for interest list events. Does nothing /// </summary> private static void DefaultSender(QueuedInterestListEvent[] eventDatas, IScenePresence presence) { // Default is no-op }
private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState) { // Don't save attachments for HG visitors, it // messes up their inventory. When a HG visitor logs // out on a foreign grid, their attachments will be // reloaded in the state they were in when they left // the home grid. This is best anyway as the visited // grid may use an incompatible script engine. bool saveChanged = sp.PresenceType != PresenceType.Npc && (m_scene.UserManagementModule == null || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID)); // Remove the object from the scene so no more updates // are sent. Doing this before the below changes will ensure // updates can't cause "HUD artefacts" m_scene.DeleteSceneObject(so, false, false); // Prepare sog for storage so.AttachedAvatar = UUID.Zero; so.RootPart.SetParentLocalId(0); so.IsAttachment = false; if (saveChanged) { // We cannot use AbsolutePosition here because that would // attempt to cross the prim as it is detached so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; }); UpdateKnownItem(sp, so, scriptedState); } // Now, remove the scripts so.RemoveScriptInstances(true); }
private void OnMakeRootAgent(IScenePresence presence) { //Only send if they are root! Util.FireAndForget(delegate { SendFriendsOnlineIfNeeded(presence.ControllingClient); }); }
private byte[] BuildLandmark (IScenePresence presence) { //See whether we have a gatekeeperURL IConfigurationService configService = m_scene.RequestModuleInterface<IConfigurationService> (); //We have one! Vector3 pos = presence.AbsolutePosition; string strdata = String.Format ( "Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}", presence.Scene.RegionInfo.RegionID, pos.X, pos.Y, pos.Z, presence.Scene.RegionInfo.RegionHandle); return Encoding.ASCII.GetBytes (strdata); }
public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights) { IClientAPI friendClient = LocateClientObject(friendID); if (friendClient != null) { bool onlineBitChanged = ((rights ^ userFlags) & (int)FriendRights.CanSeeOnline) != 0; if (onlineBitChanged) { if ((rights & (int)FriendRights.CanSeeOnline) == 1) { friendClient.SendAgentOnline(new[] { new UUID(userID) }); } else { friendClient.SendAgentOffline(new[] { new UUID(userID) }); } } else { bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0; if (canEditObjectsChanged) { friendClient.SendChangeUserRights(userID, friendID, rights); } } // Update local cache FriendInfo[] friends = GetFriends(friendID); lock (m_Friends) { #if (!ISWIN) foreach (FriendInfo finfo in friends) { if (finfo.Friend == userID.ToString()) { finfo.TheirFlags = rights; } } #else foreach (FriendInfo finfo in friends.Where(finfo => finfo.Friend == userID.ToString())) { finfo.TheirFlags = rights; } #endif } friends = GetFriends(userID); lock (m_Friends) { #if (!ISWIN) foreach (FriendInfo finfo in friends) { if (finfo.Friend == friendID.ToString()) { finfo.MyFlags = rights; } } #else foreach (FriendInfo finfo in friends.Where(finfo => finfo.Friend == friendID.ToString())) { finfo.MyFlags = rights; } #endif } //Add primFlag updates for all the prims in the sim with the owner, so that the new permissions are set up correctly IScenePresence friendSP = friendClient.Scene.GetScenePresence(friendClient.AgentId); #if (!ISWIN) foreach (ISceneEntity entity in friendClient.Scene.Entities.GetEntities()) { if (entity.OwnerID == userID) { entity.ScheduleGroupUpdateToAvatar(friendSP, PrimUpdateFlags.PrimFlags); } } #else foreach (ISceneEntity entity in friendClient.Scene.Entities.GetEntities().Where(entity => entity.OwnerID == userID)) { entity.ScheduleGroupUpdateToAvatar(friendSP, PrimUpdateFlags.PrimFlags); } #endif return(true); } return(false); }
public void TriggerOnMakeRootAgent (IScenePresence presence) { OnMakeRootAgentDelegate handlerMakeRootAgent = OnMakeRootAgent; if (handlerMakeRootAgent != null) { foreach (OnMakeRootAgentDelegate d in handlerMakeRootAgent.GetInvocationList ()) { try { d (presence); } catch (Exception e) { m_log.ErrorFormat ( "[EVENT MANAGER]: Delegate for TriggerOnMakeRootAgent failed - continuing. {0} {1}", e.ToString (), e.StackTrace); } } } }
/// <summary> /// Internal method which actually does all the work for attaching an object. /// </summary> /// <returns>The object attached.</returns> /// <param name='sp'></param> /// <param name='group'>The object to attach.</param> /// <param name='attachmentPt'></param> /// <param name='silent'></param> /// <param name='addToInventory'>If true then add object to user inventory.</param> /// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param> /// <param name='append'>Append to attachment point rather than replace.</param> private bool AttachObjectInternal( IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append) { if (group.GetSittingAvatarsCount() != 0) { if (DebugLevel > 0) m_log.WarnFormat( "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it", group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount()); return false; } Vector3 attachPos = group.AbsolutePosition; // If the attachment point isn't the same as the one previously used // set it's offset position = 0 so that it appears on the attachment point // and not in a weird location somewhere unknown. if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint) { attachPos = Vector3.Zero; } // if the attachment point is the same as previous, make sure we get the saved // position info. if (attachmentPt != 0 && attachmentPt == group.RootPart.Shape.LastAttachPoint) { attachPos = group.RootPart.AttachedPos; } // AttachmentPt 0 means the client chose to 'wear' the attachment. if (attachmentPt == (uint)AttachmentPoint.Default) { // Check object for stored attachment point attachmentPt = group.AttachmentPoint; } // if we didn't find an attach point, look for where it was last attached if (attachmentPt == 0) { attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint; attachPos = group.RootPart.AttachedPos; group.HasGroupChanged = true; } // if we still didn't find a suitable attachment point....... if (attachmentPt == 0) { // Stick it on left hand with Zero Offset from the attachment point. attachmentPt = (uint)AttachmentPoint.LeftHand; attachPos = Vector3.Zero; } group.AttachmentPoint = attachmentPt; group.AbsolutePosition = attachPos; List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt); if (attachments.Contains(group)) { if (DebugLevel > 0) m_log.WarnFormat( "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached", group.Name, group.LocalId, sp.Name, attachmentPt); return false; } // If we already have 5, remove the oldest until only 4 are left. Skip over temp ones while (attachments.Count >= 5) { if (attachments[0].FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, attachments[0]); attachments.RemoveAt(0); } // If we're not appending, remove the rest as well if (attachments.Count != 0 && !append) { foreach (SceneObjectGroup g in attachments) { if (g.FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, g); } } lock (sp.AttachmentsSyncLock) { if (addToInventory && sp.PresenceType != PresenceType.Npc) UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append); AttachToAgent(sp, group, attachmentPt, attachPos, silent); if (resumeScripts) { // Fire after attach, so we don't get messy perms dialogs // 4 == AttachedRez group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4); group.ResumeScripts(); } // Do this last so that event listeners have access to all the effects of the attachment m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID); } return true; }
void OnNewPresence(IScenePresence presence) { SendTerrainUpdatesForClient(presence); }
public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt) { if (!Enabled) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}", (AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name); // We check the attachments in the avatar appearance here rather than the objects attached to the // ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are // already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done // because pre-outfit folder viewers (most version 1 viewers) require it. bool alreadyOn = false; List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments(); foreach (AvatarAttachment existingAttachment in existingAttachments) { if (existingAttachment.ItemID == itemID) { alreadyOn = true; break; } } if (alreadyOn) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn", sp.Name, itemID, AttachmentPt); return null; } bool append = (AttachmentPt & 0x80) != 0; AttachmentPt &= 0x7f; return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append); }
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> { 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; ISceneChildEntity part; float dx; float dy; float dz; Quaternion q = SensePoint.GetRotationOffset(); 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 = !string.IsNullOrEmpty(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 ISceneEntity)) // 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 = (ent).RootChild; 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) { // add distance for sorting purposes later sensedEntities.Add(new SensedEntity(dis, ent.UUID)); } } } } return(sensedEntities); }
public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId) { DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity); }
private void EventManager_OnNewPresence(IScenePresence presence) { ScriptControllerPresenceModule m = new ScriptControllerPresenceModule(presence); presence.RegisterModuleInterface <IScriptControllerModule>(m); }
public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so) { if (so.AttachedAvatar != sp.UUID) { m_log.WarnFormat( "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}", so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName); return; } if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}", so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name); // Scripts MUST be snapshotted before the object is // removed from the scene because doing otherwise will // clobber the run flag // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from // scripts performing attachment operations at the same time. Getting object states stops the scripts. string scriptedState = PrepareScriptInstanceForSave(so, true); lock (sp.AttachmentsSyncLock) { // Save avatar attachment information // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID); bool changed = sp.Appearance.DetachAttachment(so.FromItemID); if (changed && m_scene.AvatarFactory != null) m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); sp.RemoveAttachment(so); UpdateDetachedObject(sp, so, scriptedState); } }
public ScriptControllerPresenceModule(IScenePresence sp) { m_sp = sp; m_sp.ControllingClient.OnForceReleaseControls += HandleForceReleaseControls; m_sp.Scene.EventManager.OnMakeChildAgent += EventManager_OnMakeChildAgent; }
/// <summary> /// Attach this scene object to the given avatar. /// </summary> /// <remarks> /// This isn't publicly available since attachments should always perform the corresponding inventory /// operation (to show the attach in user inventory and update the asset with positional information). /// </remarks> /// <param name="sp"></param> /// <param name="so"></param> /// <param name="attachmentpoint"></param> /// <param name="attachOffset"></param> /// <param name="silent"></param> private void AttachToAgent( IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}", so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos); so.DetachFromBackup(); // Remove from database and parcel prim count m_scene.DeleteFromStorage(so.UUID); m_scene.EventManager.TriggerParcelPrimCountTainted(); so.AttachedAvatar = sp.UUID; if (so.RootPart.PhysActor != null) so.RootPart.RemoveFromPhysics(); so.AbsolutePosition = attachOffset; so.RootPart.AttachedPos = attachOffset; so.IsAttachment = true; so.RootPart.SetParentLocalId(sp.LocalId); so.AttachmentPoint = attachmentpoint; sp.AddAttachment(so); if (!silent) { if (so.HasPrivateAttachmentPoint) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}", so.Name, sp.Name, so.AttachmentPoint); // As this scene object can now only be seen by the attaching avatar, tell everybody else in the // scene that it's no longer in their awareness. m_scene.ForEachClient( client => { if (client.AgentId != so.AttachedAvatar) client.SendKillObject(new List<uint>() { so.LocalId }); }); } // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update // will succeed, as that will not update if an attachment is selected. so.IsSelected = false; // fudge.... so.ScheduleGroupForFullUpdate(); } // In case it is later dropped again, don't let // it get cleaned up so.RootPart.RemFlag(PrimFlags.TemporaryOnRez); }
protected void EventManager_OnNewPresence(IScenePresence presence) { presence.RegisterModuleInterface <PerClientSelectionParticles>(new PerClientSelectionParticles(presence, this)); }
public UUID CreateAvatar(string firstName, string lastName, IScene scene, AvatarAppearance avatarApp, UUID creatorID, Vector3 startPos) { //Add the circuit data so they can login AgentCircuitData m_aCircuitData = new AgentCircuitData { IsChildAgent = false, CircuitCode = (uint)Util.RandomClass.Next() }; //Create the new bot data BotClientAPI m_character = new BotClientAPI(scene, m_aCircuitData); m_character.Name = firstName + " " + lastName; m_aCircuitData.AgentID = m_character.AgentId; //Set up appearance var origOwner = avatarApp.Owner; avatarApp.Owner = m_character.AgentId; List <AvatarAttachment> attachments = avatarApp.GetAttachments(); avatarApp.ClearAttachments(); // get original attachments foreach (AvatarAttachment t in attachments) { InventoryItemBase item = scene.InventoryService.GetItem(origOwner, t.ItemID); if (item != null) { item.ID = UUID.Random(); item.Owner = m_character.AgentId; item.Folder = UUID.Zero; scene.InventoryService.AddCacheItemAsync(item); //Now fix the ItemID avatarApp.SetAttachment(t.AttachPoint, item.ID, t.AssetID); } } scene.AuthenticateHandler.AgentCircuits.Add(m_character.CircuitCode, m_aCircuitData); //This adds them to the scene and sets them inworld AddAndWaitUntilAgentIsAdded(scene, m_character); IScenePresence SP = scene.GetScenePresence(m_character.AgentId); if (SP == null) { return(UUID.Zero); //Failed! } IAvatarAppearanceModule appearance = SP.RequestModuleInterface <IAvatarAppearanceModule>(); appearance.Appearance = avatarApp; appearance.InitialHasWearablesBeenSent = true; Bot bot = new Bot(); bot.Initialize(SP, creatorID); SP.MakeRootAgent(startPos, false, true); //Move them SP.Teleport(startPos); foreach (var presence in scene.GetScenePresences()) { presence.SceneViewer.QueuePresenceForUpdate(SP, PrimUpdateFlags.ForcedFullUpdate); } IAttachmentsModule attModule = SP.Scene.RequestModuleInterface <IAttachmentsModule>(); if (attModule != null) { foreach (AvatarAttachment att in attachments) { attModule.RezSingleAttachmentFromInventory(SP.ControllingClient, att.ItemID, att.AssetID, 0, true); } } //Save them in the bots list m_bots.Add(m_character.AgentId, bot); AddTagToBot(m_character.AgentId, "AllBots", bot.AvatarCreatorID); MainConsole.Instance.InfoFormat("[BotManager]: Added bot {0} to region {1}", m_character.Name, scene.RegionInfo.RegionName); //Return their UUID return(m_character.AgentId); }
private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append) { // Add the new attachment to inventory if we don't already have it. UUID newAttachmentItemID = group.FromItemID; if (newAttachmentItemID == UUID.Zero) newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID; ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append); }
public AvatarAttachments(IScenePresence SP) { }
public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}", rezlist.Count, sp.Name, m_scene.Name); foreach (KeyValuePair<UUID, uint> rez in rezlist) { RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value); } }
public ISceneEntity RezSingleAttachmentFromInventory( IClientAPI remoteClient, UUID itemID, UUID assetID, int AttachmentPt, bool updateUUIDs) { MainConsole.Instance.DebugFormat( "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}", (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name); IInventoryAccessModule invAccess = m_scene.RequestModuleInterface <IInventoryAccessModule>(); if (invAccess != null) { InventoryItemBase item = null; ISceneEntity objatt = assetID == UUID.Zero ? invAccess.CreateObjectFromInventory(remoteClient, itemID, out item) : invAccess.CreateObjectFromInventory(remoteClient, itemID, assetID, null); if (objatt != null) { #region Set up object for attachment status if (item != null) { assetID = item.AssetID; // 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. objatt.RootChild.Name = item.Name; objatt.RootChild.Description = item.Description; } objatt.RootChild.Flags |= PrimFlags.Phantom; objatt.RootChild.IsAttachment = true; objatt.SetFromItemID(itemID, assetID); List <ISceneChildEntity> partList = new List <ISceneChildEntity>(objatt.ChildrenEntities()); foreach (ISceneChildEntity part in partList) { part.AttachedAvatar = remoteClient.AgentId; } objatt.SetGroup(remoteClient.ActiveGroupId, remoteClient.AgentId, false); if (objatt.RootChild.OwnerID != remoteClient.AgentId) { //Need to kill the for sale here objatt.RootChild.ObjectSaleType = 0; objatt.RootChild.SalePrice = 10; if (m_scene.Permissions.PropagatePermissions()) { if (item == null) { item = m_scene.InventoryService.GetItem(remoteClient.AgentId, itemID); } if (item == null) { return(null); } if ((item.CurrentPermissions & 8) != 0) { foreach (ISceneChildEntity part in partList) { part.EveryoneMask = item.EveryOnePermissions; part.NextOwnerMask = item.NextPermissions; part.GroupMask = 0; // DO NOT propagate here } } objatt.ApplyNextOwnerPermissions(); } } foreach (ISceneChildEntity part in partList) { if (part.OwnerID != remoteClient.AgentId) { part.LastOwnerID = part.OwnerID; part.OwnerID = remoteClient.AgentId; part.Inventory.ChangeInventoryOwner(remoteClient.AgentId); } } objatt.RootChild.TrimPermissions(); objatt.RootChild.IsAttachment = true; objatt.IsDeleted = false; //Update the ItemID with the new item objatt.SetFromItemID(itemID, assetID); //DO NOT SEND THIS KILL ENTITY // If we send this, when someone copies an inworld object, then wears it, the inworld objects disapepars // If a bug is caused by this, we need to figure out some other workaround. //SendKillEntity(objatt.RootChild); //We also have to reset the IDs so that it doesn't have the same IDs as one inworld (possibly)! ISceneEntity[] atts = GetAttachmentsForAvatar(remoteClient.AgentId); foreach (var obj in atts) { if (obj.UUID == objatt.UUID) { updateUUIDs = false; //If the user is already wearing it, don't readd } } bool forceUpdateOnNextDeattach = false; try { bool foundDuplicate = false; foreach (var obj in atts) { if (obj.RootChild.FromUserInventoryItemID == objatt.RootChild.FromUserInventoryItemID) { foundDuplicate = true; } } IEntity e; if (!m_scene.SceneGraph.TryGetEntity(objatt.UUID, out e)) //if (updateUUIDs) { foreach (var prim in objatt.ChildrenEntities()) { prim.LocalId = 0; } bool success = m_scene.SceneGraph.RestorePrimToScene(objatt, false); if (!success) { MainConsole.Instance.Error("[AttachmentModule]: Failed to add attachment " + objatt.Name + " for user " + remoteClient.Name + "!"); return(null); } } else { if (!foundDuplicate) { if (m_scene.SceneGraph.AddPrimToScene(objatt)) { forceUpdateOnNextDeattach = true; } //If the user has information stored about this object, we need to force updating next time } else { if (e as ISceneEntity != null) { (e as ISceneEntity).ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate); } return(e as ISceneEntity); //It was already added } /*foreach (var prim in objatt.ChildrenEntities()) * prim.LocalId = 0; * bool success = m_scene.SceneGraph.RestorePrimToScene(objatt, true); * if (!success) * MainConsole.Instance.Error("[AttachmentModule]: Failed to add attachment " + objatt.Name + " for user " + remoteClient.Name + "!"); */ } } catch { } //If we updated the attachment, we need to save the change IScenePresence presence = m_scene.GetScenePresence(remoteClient.AgentId); if (presence != null) { FindAttachmentPoint(remoteClient, objatt.LocalId, objatt, AttachmentPt, assetID, forceUpdateOnNextDeattach, false); } else { objatt = null; //Presence left, kill the attachment } #endregion } else { MainConsole.Instance.WarnFormat( "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}", itemID, remoteClient.Name, AttachmentPt); } return(objatt); } return(null); }
public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}", sp.UUID, soLocalId); SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId); if (so == null) return; if (so.AttachedAvatar != sp.UUID) return; UUID inventoryID = so.FromItemID; // As per Linden spec, drop is disabled for temp attachs if (inventoryID == UUID.Zero) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}", so.Name, so.LocalId, inventoryID); lock (sp.AttachmentsSyncLock) { if (!m_scene.Permissions.CanRezObject( so.PrimCount, sp.UUID, sp.AbsolutePosition)) return; bool changed = false; if (inventoryID != UUID.Zero) changed = sp.Appearance.DetachAttachment(inventoryID); if (changed && m_scene.AvatarFactory != null) m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); sp.RemoveAttachment(so); so.FromItemID = UUID.Zero; SceneObjectPart rootPart = so.RootPart; so.AbsolutePosition = absolutePos; if (absoluteRot != Quaternion.Identity) { so.UpdateGroupRotationR(absoluteRot); } so.AttachedAvatar = UUID.Zero; rootPart.SetParentLocalId(0); so.ClearPartAttachmentData(); rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive); so.HasGroupChanged = true; so.RootPart.Shape.LastAttachPoint = (byte)so.AttachmentPoint; rootPart.Rezzed = DateTime.Now; rootPart.RemFlag(PrimFlags.TemporaryOnRez); so.AttachToBackup(); m_scene.EventManager.TriggerParcelPrimCountTainted(); rootPart.ScheduleFullUpdate(); rootPart.ClearUndoState(); List<UUID> uuids = new List<UUID>(); uuids.Add(inventoryID); m_scene.InventoryService.DeleteItems(sp.UUID, uuids); sp.ControllingClient.SendRemoveInventoryItem(inventoryID); } m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero); }
/// <summary> /// Attach the object to the avatar /// </summary> /// <param name="remoteClient">The client that is having the attachment done</param> /// <param name="localID">The localID (SceneObjectPart) that is being attached (for the attach script event)</param> /// <param name="group">The group (SceneObjectGroup) that is being attached</param> /// <param name="AttachmentPt">The point to where the attachment will go</param> /// <param name="assetID" /> /// <param name="forceUpdatePrim">Force updating of the prim the next time the user attempts to deattach it</param> /// <param name="isTempAttach">Is a temporary attachment</param> protected void FindAttachmentPoint(IClientAPI remoteClient, uint localID, ISceneEntity group, int AttachmentPt, UUID assetID, bool forceUpdatePrim, bool isTempAttach) { //Make sure that we arn't over the limit of attachments ISceneEntity[] attachments = GetAttachmentsForAvatar(remoteClient.AgentId); if (attachments.Length + 1 > m_maxNumberOfAttachments) { //Too many remoteClient.SendAgentAlertMessage( "You are wearing too many attachments. Take one off to attach this object", false); return; } Vector3 attachPos = group.GetAttachmentPos(); bool hasMultipleAttachmentsSet = (AttachmentPt & 0x7f) != 0 || AttachmentPt == 0; if (!m_allowMultipleAttachments) { hasMultipleAttachmentsSet = false; } AttachmentPt &= 0x7f; //Disable it! Its evil! //Did the attachment change position or attachment point? bool changedPositionPoint = false; // If the attachment point isn't the same as the one previously used // set it's offset position = 0 so that it appears on the attachment point // and not in a weird location somewhere unknown. //Simplier terms: the attachment point changed, set it to the default 0,0,0 location if (AttachmentPt != 0 && AttachmentPt != (group.GetAttachmentPoint() & 0x7f)) { attachPos = Vector3.Zero; changedPositionPoint = true; } else { // AttachmentPt 0 means the client chose to 'wear' the attachment. if (AttachmentPt == 0) { // Check object for stored attachment point AttachmentPt = group.GetSavedAttachmentPoint() & 0x7f; attachPos = group.GetAttachmentPos(); } //Check state afterwards... use the newer GetSavedAttachmentPoint and Pos above first if (AttachmentPt == 0) { // Check object for older stored attachment point AttachmentPt = group.RootChild.Shape.State & 0x7f; //attachPos = group.AbsolutePosition; } // if we still didn't find a suitable attachment point, force it to the default //This happens on the first time an avatar 'wears' an object if (AttachmentPt == 0) { // Stick it on right hand with Zero Offset from the attachment point. AttachmentPt = (int)AttachmentPoint.RightHand; //Default location attachPos = Vector3.Zero; changedPositionPoint = true; } } MainConsole.Instance.DebugFormat( "[ATTACHMENTS MODULE]: Retrieved single object {0} for attachment to {1} on point {2} localID {3}", group.Name, remoteClient.Name, AttachmentPt, group.LocalId); //Update where we are put group.SetAttachmentPoint((byte)AttachmentPt); //Fix the position with the one we found group.AbsolutePosition = attachPos; // Remove any previous attachments IScenePresence presence = m_scene.GetScenePresence(remoteClient.AgentId); if (presence == null) { return; } UUID itemID = UUID.Zero; //Check for multiple attachment bits and whether we should remove the old if (!hasMultipleAttachmentsSet) { foreach (ISceneEntity grp in attachments) { if (grp.GetAttachmentPoint() == (byte)AttachmentPt) { itemID = grp.RootChild.FromUserInventoryItemID; break; } } if (itemID != UUID.Zero) { DetachSingleAttachmentToInventory(itemID, remoteClient); } } itemID = group.RootChild.FromUserInventoryItemID; group.RootChild.AttachedAvatar = presence.UUID; List <ISceneChildEntity> parts = group.ChildrenEntities(); foreach (ISceneChildEntity t in parts) { t.AttachedAvatar = presence.UUID; } if (group.RootChild.PhysActor != null) { m_scene.PhysicsScene.DeletePrim(group.RootChild.PhysActor); group.RootChild.PhysActor = null; } group.RootChild.AttachedPos = attachPos; group.RootChild.IsAttachment = true; group.AbsolutePosition = attachPos; group.RootChild.SetParentLocalId(presence.LocalId); group.SetAttachmentPoint(Convert.ToByte(AttachmentPt)); // Killing it here will cause the client to deselect it // It then reappears on the avatar, deselected // through the full update below // if (group.IsSelected) { foreach (ISceneChildEntity part in group.ChildrenEntities()) { part.CreateSelected = true; } } //NOTE: This MUST be here, otherwise we limit full updates during attachments when they are selected and it will block the first update. // So until that is changed, this MUST stay. The client will instantly reselect it, so this value doesn't stay borked for long. group.IsSelected = false; if (!isTempAttach) { if (itemID == UUID.Zero) { //Delete the object inworld to inventory List <ISceneEntity> groups = new List <ISceneEntity>(1) { group }; IInventoryAccessModule inventoryAccess = m_scene.RequestModuleInterface <IInventoryAccessModule>(); if (inventoryAccess != null) { inventoryAccess.DeleteToInventory(DeRezAction.AcquireToUserInventory, UUID.Zero, groups, remoteClient.AgentId, out itemID); } } else { //it came from an item, we need to start the scripts // Fire after attach, so we don't get messy perms dialogs // 4 == AttachedRez group.CreateScriptInstances(0, true, StateSource.AttachedRez, UUID.Zero, false); } if (UUID.Zero == itemID) { MainConsole.Instance.Error( "[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID."); remoteClient.SendAgentAlertMessage( "Unable to save attachment. Error inventory item ID.", false); return; } // XXYY!! if (assetID == UUID.Zero) { assetID = m_scene.InventoryService.GetItemAssetID(remoteClient.AgentId, itemID); //Update the ItemID with the new item group.SetFromItemID(itemID, assetID); } } else { // Fire after attach, so we don't get messy perms dialogs // 4 == AttachedRez group.CreateScriptInstances(0, true, StateSource.AttachedRez, UUID.Zero, false); group.RootChild.FromUserInventoryItemID = UUID.Zero; } AvatarAttachments attPlugin = presence.RequestModuleInterface <AvatarAttachments>(); if (attPlugin != null) { attPlugin.AddAttachment(group); presence.SetAttachments(attPlugin.Get()); if (!isTempAttach) { IAvatarAppearanceModule appearance = presence.RequestModuleInterface <IAvatarAppearanceModule>(); appearance.Appearance.SetAttachments(attPlugin.Get()); AvatarFactory.QueueAppearanceSave(remoteClient.AgentId); } } // In case it is later dropped again, don't let // it get cleaned up group.RootChild.RemFlag(PrimFlags.TemporaryOnRez); group.HasGroupChanged = changedPositionPoint || forceUpdatePrim; //Now recreate it so that it is selected group.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate); m_scene.EventManager.TriggerOnAttach(localID, group.RootChild.FromUserInventoryItemID, remoteClient.AgentId); }
/// <summary> /// Update the attachment asset for the new sog details if they have changed. /// </summary> /// <remarks> /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects, /// these details are not stored on the region. /// </remarks> /// <param name="sp"></param> /// <param name="grp"></param> /// <param name="saveAllScripted"></param> private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState) { if (grp.FromItemID == UUID.Zero) { // We can't save temp attachments grp.HasGroupChanged = false; return; } // Saving attachments for NPCs messes them up for the real owner! INPCModule module = m_scene.RequestModuleInterface<INPCModule>(); if (module != null) { if (module.IsNPC(sp.UUID, m_scene)) return; } if (grp.HasGroupChanged) { m_log.DebugFormat( "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}", grp.UUID, grp.AttachmentPoint); string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState); InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID); item = m_scene.InventoryService.GetItem(item); if (item != null) { AssetBase asset = m_scene.CreateAsset( grp.GetPartName(grp.LocalId), grp.GetPartDescription(grp.LocalId), (sbyte)AssetType.Object, Utils.StringToBytes(sceneObjectXml), sp.UUID); m_scene.AssetService.Store(asset); item.AssetID = asset.FullID; item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; item.InvType = (int)InventoryType.Object; m_scene.InventoryService.UpdateItem(item); // If the name of the object has been changed whilst attached then we want to update the inventory // item in the viewer. if (sp.ControllingClient != null) sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } grp.HasGroupChanged = false; // Prevent it being saved over and over } else if (DebugLevel > 0) { m_log.DebugFormat( "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}", grp.UUID, grp.AttachmentPoint); } }
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID, uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags, int queryclassifiedPrice, IClientAPI remoteClient) { IScenePresence p = remoteClient.Scene.GetScenePresence(remoteClient.AgentId); if (p == null) { return; //Just fail } IScheduledMoneyModule scheduledMoneyModule = p.Scene.RequestModuleInterface <IScheduledMoneyModule>(); IMoneyModule moneyModule = p.Scene.RequestModuleInterface <IMoneyModule>(); Classified classcheck = ProfileFrontend.GetClassified(queryclassifiedID); if (((queryclassifiedFlags & 32) != 32) && moneyModule != null) { //Single week if (!moneyModule.Charge(remoteClient.AgentId, queryclassifiedPrice, "Add Classified", TransactionType.ClassifiedCharge)) { remoteClient.SendAlertMessage("You do not have enough money to create this classified."); return; } } else if (scheduledMoneyModule != null) { //Auto-renew if (classcheck != null) { scheduledMoneyModule.RemoveFromScheduledCharge("Classified" + queryclassifiedID); } if (!scheduledMoneyModule.Charge(remoteClient.AgentId, queryclassifiedPrice, "Add Classified (" + queryclassifiedID + ")", 7, TransactionType.ClassifiedCharge, "Classified" + queryclassifiedID, true)) { remoteClient.SendAlertMessage("You do not have enough money to create this classified."); return; } } UUID creatorUUID = remoteClient.AgentId; UUID classifiedUUID = queryclassifiedID; uint category = queryCategory; string name = queryName; string description = queryDescription; uint parentestate = queryParentEstate; UUID snapshotUUID = querySnapshotID; string simname = remoteClient.Scene.RegionInfo.RegionName; Vector3 globalpos = queryGlobalPos; byte classifiedFlags = queryclassifiedFlags; int classifiedPrice = queryclassifiedPrice; UUID parceluuid = p.CurrentParcelUUID; string parcelname = "Unknown"; IParcelManagementModule parcelManagement = remoteClient.Scene.RequestModuleInterface <IParcelManagementModule>(); if (parcelManagement != null) { ILandObject parcel = parcelManagement.GetLandObject(p.AbsolutePosition.X, p.AbsolutePosition.Y); if (parcel != null) { parcelname = parcel.LandData.Name; parceluuid = parcel.LandData.GlobalID; } } uint creationdate = (uint)Util.UnixTimeSinceEpoch(); uint expirationdate = (uint)Util.UnixTimeSinceEpoch() + (365 * 24 * 60 * 60); Classified classified = new Classified { ClassifiedUUID = classifiedUUID, CreatorUUID = creatorUUID, CreationDate = creationdate, ExpirationDate = expirationdate, Category = category, Name = name, Description = description, ParcelUUID = parceluuid, ParentEstate = parentestate, SnapshotUUID = snapshotUUID, SimName = simname, GlobalPos = globalpos, ParcelName = parcelname, ClassifiedFlags = classifiedFlags, PriceForListing = classifiedPrice, ScopeID = remoteClient.ScopeID }; ProfileFrontend.AddClassified(classified); }
/// <summary> /// Add a scene object as a new attachment in the user inventory. /// </summary> /// <param name="remoteClient"></param> /// <param name="grp"></param> /// <returns>The user inventory item created that holds the attachment.</returns> private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp) { if (m_invAccessModule == null) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}", grp.Name, grp.LocalId, sp.Name); InventoryItemBase newItem = m_invAccessModule.CopyToInventory( DeRezAction.TakeCopy, m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID, new List<SceneObjectGroup> { grp }, sp.ControllingClient, true)[0]; // sets itemID so client can show item as 'attached' in inventory grp.FromItemID = newItem.ID; return newItem; }
IClientAPI FindClient(UUID agentID) { IScenePresence presence = m_Scene.GetScenePresence(agentID); return((presence != null && !presence.IsChildAgent) ? presence.ControllingClient : null); }
protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal( IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append) { if (m_invAccessModule == null) return null; SceneObjectGroup objatt; if (itemID != UUID.Zero) objatt = m_invAccessModule.RezObject(sp.ControllingClient, itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, false, false, sp.UUID, true); else objatt = m_invAccessModule.RezObject(sp.ControllingClient, null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, false, false, sp.UUID, true); if (objatt == null) { m_log.WarnFormat( "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}", itemID, sp.Name, attachmentPt); return null; } else if (itemID == UUID.Zero) { // We need to have a FromItemID for multiple attachments on a single attach point to appear. This is // true on Singularity 1.8.5 and quite possibly other viewers as well. As NPCs don't have an inventory // we will satisfy this requirement by inserting a random UUID. objatt.FromItemID = UUID.Random(); } if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}", objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name); // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller. objatt.HasGroupChanged = false; bool tainted = false; if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint) tainted = true; // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal // course of events. If not, then it's probably not worth trying to recover the situation // since this is more likely to trigger further exceptions and confuse later debugging. If // exceptions can be thrown in expected error conditions (not NREs) then make this consistent // since other normal error conditions will simply return false instead. // This will throw if the attachment fails try { AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append); } catch (Exception e) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}", objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace); // Make sure the object doesn't stick around and bail sp.RemoveAttachment(objatt); m_scene.DeleteSceneObject(objatt, false); return null; } if (tainted) objatt.HasGroupChanged = true; if (ThrottlePer100PrimsRezzed > 0) { int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed); if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}", throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name); Thread.Sleep(throttleMs); } return objatt; }
void OnMakeRootAgent(IScenePresence presence) { presence.ControllingClient.SendMoneyBalance(UUID.Zero, true, new byte[0], (int)m_connector.GetUserCurrency(presence.UUID).Amount); }
private void SendTerrainPacket(QueuedInterestListEvent[] eventDatas, IScenePresence presence) { const int PATCHES_PER_PACKET = 3; if (!(presence is LLAgent) || presence.InterestList == null) return; LLAgent agent = (LLAgent)presence; List<int> patches = new List<int>(PATCHES_PER_PACKET); for (int i = 0; i < eventDatas.Length; i++) { int[] state = (int[])eventDatas[i].Event.State; int x = state[0]; int y = state[1]; patches.Add(y * 16 + x); if (patches.Count == PATCHES_PER_PACKET || i == eventDatas.Length - 1) { LayerDataPacket packet = TerrainCompressor.CreateLandPacket(m_terrain.GetHeightmap(), patches.ToArray()); m_udp.SendPacket(agent, packet, ThrottleCategory.Land, false); patches = new List<int>(PATCHES_PER_PACKET); } } }
OSDMap syncRecievedService_OnMessageReceived(OSDMap message) { string method = message ["Method"]; if (method == "UpdateMoneyBalance") { UUID agentID = message ["AgentID"]; int Amount = message ["Amount"]; string Message = message ["Message"]; UUID TransactionID = message ["TransactionID"]; IDialogModule dialogModule = GetSceneFor(agentID).RequestModuleInterface <IDialogModule> (); IScenePresence sp = GetSceneFor(agentID).GetScenePresence(agentID); if (sp != null) { if (dialogModule != null && !string.IsNullOrEmpty(Message)) { dialogModule.SendAlertToUser(agentID, Message); } sp.ControllingClient.SendMoneyBalance(TransactionID, true, Utils.StringToBytes(Message), Amount); } } else if (method == "GetLandData") { MainConsole.Instance.Info(message); UUID agentID = message["AgentID"]; IScene region = GetSceneFor(agentID); MainConsole.Instance.Info("Region: " + region.RegionInfo.RegionName); IParcelManagementModule parcelManagement = region.RequestModuleInterface <IParcelManagementModule> (); if (parcelManagement != null) { IScenePresence sp = region.GetScenePresence(agentID); if (sp != null) { MainConsole.Instance.DebugFormat("sp parcel UUID: {0} Pos: {1}, {2}", sp.CurrentParcelUUID, sp.AbsolutePosition.X, sp.AbsolutePosition.Y); ILandObject lo = sp.CurrentParcel; if (lo == null) { // try for a position fix lo = parcelManagement.GetLandObject((int)sp.AbsolutePosition.X, (int)sp.AbsolutePosition.Y); } if (lo != null) { if ((lo.LandData.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale) { if (lo.LandData.AuthBuyerID != UUID.Zero && lo.LandData.AuthBuyerID != agentID) { return new OSDMap { new KeyValuePair <string, OSD> ("Success", false) } } ; OSDMap map = lo.LandData.ToOSD(); map ["Success"] = true; return(map); } } } } return(new OSDMap { new KeyValuePair <string, OSD>("Success", false) }); } return(null); } IScene GetSceneFor(UUID userID) { foreach (IScene scene in m_scenes) { var sp = scene.GetScenePresence(userID); if (sp != null && !sp.IsChildAgent) { return(scene); } } if (m_scenes.Count == 0) { MainConsole.Instance.Debug("User not present in any regions??"); return(null); } MainConsole.Instance.Debug("Returning scene[0]: " + m_scenes [0].RegionInfo.RegionName); return(m_scenes[0]); }
public void TriggerAvatarEnteringNewParcel (IScenePresence avatar, int localLandID, UUID regionID) { AvatarEnteringNewParcel handlerAvatarEnteringNewParcel = OnAvatarEnteringNewParcel; if (handlerAvatarEnteringNewParcel != null) { foreach (AvatarEnteringNewParcel d in handlerAvatarEnteringNewParcel.GetInvocationList ()) { try { d (avatar, localLandID, regionID); } catch (Exception e) { m_log.ErrorFormat ( "[EVENT MANAGER]: Delegate for TriggerAvatarEnteringNewParcel failed - continuing. {0} {1}", e.ToString (), e.StackTrace); } } } }
public bool OnNewChatMessageFromWorld(OSChatMessage c, out OSChatMessage newc) { IScenePresence SP = c.Scene.GetScenePresence(c.SenderUUID); if (SP != null) { if (!SP.IsChildAgent) { //Check that the agent is allows to speak in this reigon if (SP.GodLevel != 0 && !!m_authorizedSpeakers.Contains(c.SenderUUID)) { m_authorizedSpeakers.Add(c.SenderUUID); } if (SP.GodLevel != 0 && !m_authList.Contains(c.SenderUUID)) { m_authList.Add(c.SenderUUID); } if (!m_authorizedSpeakers.Contains(c.SenderUUID)) { newc = c; //They can't talk, so block it return(false); } } } if (c.Message.Contains("Chat.")) { if (!m_useAuth || m_authList.Contains(c.SenderUUID)) { IScenePresence senderSP; c.Scene.TryGetScenePresence(c.SenderUUID, out senderSP); string[] message = c.Message.Split('.'); if (message[1] == "SayDistance") { chatModule.SayDistance = Convert.ToInt32(message[2]); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[1] + " changed.", ChatSourceType.System, -1); } if (message[1] == "WhisperDistance") { chatModule.WhisperDistance = Convert.ToInt32(message[2]); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[1] + " changed.", ChatSourceType.System, -1); } if (message[1] == "ShoutDistance") { chatModule.ShoutDistance = Convert.ToInt32(message[2]); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[1] + " changed.", ChatSourceType.System, -1); } //Add the user to the list of allowed speakers and 'chat' admins if (message[1] == "AddToAuth") { IScenePresence NewSP; c.Scene.TryGetAvatarByName(message[2], out NewSP); m_authList.Add(NewSP.UUID); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[2] + " added.", ChatSourceType.System, -1); } if (message[1] == "RemoveFromAuth") { IScenePresence NewSP; c.Scene.TryGetAvatarByName(message[2], out NewSP); m_authList.Remove(NewSP.UUID); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[2] + " added.", ChatSourceType.System, -1); } //Block chat from those not in the auth list if (message[1] == "BlockChat") { m_blockChat = true; chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, "Chat blocked.", ChatSourceType.System, -1); } //Allow chat from all again if (message[1] == "AllowChat") { m_blockChat = false; chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, "Chat allowed.", ChatSourceType.System, -1); } //Remove speaking priviledges from an individual if (message[1] == "RevokeSpeakingRights") { IScenePresence NewSP; c.Scene.TryGetAvatarByName(message[2], out NewSP); m_authorizedSpeakers.Remove(NewSP.UUID); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[2] + " - revoked.", ChatSourceType.System, -1); } //Allow an individual to speak again if (message[1] == "GiveSpeakingRights") { IScenePresence NewSP; c.Scene.TryGetAvatarByName(message[2], out NewSP); m_authorizedSpeakers.Add(NewSP.UUID); chatModule.TrySendChatMessage(senderSP, c.Position, UUID.Zero, "WhiteCoreChat", ChatTypeEnum.Region, message[2] + " - revoked.", ChatSourceType.System, -1); } } newc = c; //Block commands from normal chat return(false); } if (SP != null) { //Add the god prefix if (SP.GodLevel != 0 && m_indicategod) { c.Message = m_godPrefix + c.Message; } } newc = c; return(true); }
public void TriggerSignificantClientMovement (IScenePresence presence) { SignificantClientMovement handlerSignificantClientMovement = OnSignificantClientMovement; if (handlerSignificantClientMovement != null) { foreach (SignificantClientMovement d in handlerSignificantClientMovement.GetInvocationList ()) { try { d (presence); } catch (Exception e) { m_log.ErrorFormat ( "[EVENT MANAGER]: Delegate for TriggerSignificantClientMovement failed - continuing. {0} {1}", e.ToString (), e.StackTrace); } } } }
void OnInstantMessage(IClientAPI client, GridInstantMessage im) { //MainConsole.Instance.InfoFormat("[Inventory transfer]: OnInstantMessage {0}", im.dialog); IScene clientScene = FindClientScene(client.AgentId); if (clientScene == null) { // Something seriously wrong here. MainConsole.Instance.DebugFormat("[Inventory transfer]: Cannot find originating user scene"); return; } if (im.Dialog == (byte)InstantMessageDialog.InventoryOffered) { //MainConsole.Instance.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0])); if (im.BinaryBucket.Length < 17) // Invalid { MainConsole.Instance.DebugFormat("[Inventory transfer]: Invalid length {0} for asset type {1}", im.BinaryBucket.Length, ((AssetType)im.BinaryBucket [0])); return; } UUID recipientID = im.ToAgentID; IScenePresence recipientUser = null; IScene recipientUserScene = FindClientScene(recipientID); if (recipientUserScene != null) { recipientUser = recipientUserScene.GetScenePresence(recipientID); } UUID copyID; // give the item to the recipient, assuming they will accept it // First byte is the asset type AssetType assetType = (AssetType)im.BinaryBucket [0]; if (assetType == AssetType.Folder) { var folderID = new UUID(im.BinaryBucket, 1); if (im.SessionID == folderID) { // this must be an offline message being processed. just pass it through if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im); } return; } MainConsole.Instance.DebugFormat( "[Inventory transfer]: Inserting original folder {0} into agent {1}'s inventory", folderID, im.ToAgentID); clientScene.InventoryService.GiveInventoryFolderAsync( recipientID, client.AgentId, folderID, UUID.Zero, (folder) => { if (folder == null) { client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false); return; } // The outgoing binary bucket should contain only the byte which signals an asset folder is // being copied and the following bytes for the copied folder's UUID copyID = folder.ID; byte [] copyIDBytes = copyID.GetBytes(); im.BinaryBucket = new byte [1 + copyIDBytes.Length]; im.BinaryBucket [0] = (byte)AssetType.Folder; Array.Copy(copyIDBytes, 0, im.BinaryBucket, 1, copyIDBytes.Length); im.SessionID = copyID; if (moneyService != null) { moneyService.Transfer(im.ToAgentID, im.FromAgentID, 0, "Inworld inventory folder transfer", TransactionType.GiveInventory); } if (recipientUser != null) { // user is on this region... update them recipientUser.ControllingClient.SendBulkUpdateInventory(folder); recipientUser.ControllingClient.SendInstantMessage(im); } else if (m_TransferModule != null) { // user is not in this region or not online... let them know m_TransferModule.SendInstantMessage(im); } }); } else { // Inventory item // First byte of the array is probably the item type // Next 16 bytes are the UUID var itemID = new UUID(im.BinaryBucket, 1); if (im.SessionID == itemID) { // this must be an offline message being processed. just pass it through if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im); } return; } MainConsole.Instance.DebugFormat( "[Inventory transfer]: (giving) Inserting item {0} into agent {1}'s inventory", itemID, im.ToAgentID); clientScene.InventoryService.GiveInventoryItemAsync( im.ToAgentID, im.FromAgentID, itemID, UUID.Zero, false, (itemCopy) => { if (itemCopy == null) { MainConsole.Instance.DebugFormat( "[Inventory transfer]: (giving) Unable to find item {0} to give to agent {1}'s inventory", itemID, im.ToAgentID); client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false); return; } copyID = itemCopy.ID; Array.Copy(copyID.GetBytes(), 0, im.BinaryBucket, 1, 16); im.SessionID = itemCopy.ID; if (moneyService != null) { moneyService.Transfer(im.ToAgentID, im.FromAgentID, 0, "Inworld inventory item transfer", TransactionType.GiveInventory); } if (recipientUser != null) { // user is on this region... recipientUser.ControllingClient.SendBulkUpdateInventory(itemCopy); recipientUser.ControllingClient.SendInstantMessage(im); } else if (m_TransferModule != null) { // user is not present on this region or offline... let them know m_TransferModule.SendInstantMessage(im); } }); } } else if (im.Dialog == (byte)InstantMessageDialog.InventoryAccepted) { IScenePresence user = clientScene.GetScenePresence(im.ToAgentID); MainConsole.Instance.DebugFormat("[Inventory transfer]: Acceptance message received"); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im); } } } else if (im.Dialog == (byte)InstantMessageDialog.InventoryDeclined) { // Here, the recipient is local and we can assume that the // inventory is loaded. Courtesy of the above bulk update, // It will have been pushed to the client, too // IInventoryService invService = clientScene.InventoryService; MainConsole.Instance.DebugFormat("[Inventory transfer]: Declined message received"); InventoryFolderBase trashFolder = invService.GetFolderForType(client.AgentId, InventoryType.Unknown, FolderType.Trash); UUID inventoryID = im.SessionID; // The inventory item/folder, back from it's trip InventoryItemBase item = invService.GetItem(client.AgentId, inventoryID); InventoryFolderBase folder = null; // cannot delete if we do not have somewhere to put it if (trashFolder != null) { // Deleting an item if (item != null) { item.Folder = trashFolder.ID; var uuids = new List <UUID> { item.ID }; invService.DeleteItems(item.Owner, uuids); // delete the item from the client's inventory ILLClientInventory inventory = client.Scene.RequestModuleInterface <ILLClientInventory> (); if (inventory != null) { inventory.AddInventoryItemAsync(client, item); // send an inventory update to the client } } else { // deleting a folder folder = new InventoryFolderBase(inventoryID, client.AgentId); folder = invService.GetFolder(folder); if (folder != null) { folder.ParentID = trashFolder.ID; invService.MoveFolder(folder); client.SendBulkUpdateInventory(folder); } } } if ((item == null && folder == null) | trashFolder == null) { string reason = string.Empty; if (trashFolder == null) { reason += " Trash folder not found."; } if (item == null) { reason += " Item not found."; } if (folder == null) { reason += " Folder not found."; } client.SendAgentAlertMessage("Unable to delete received inventory" + reason, false); } if (moneyService != null) { moneyService.Transfer(im.ToAgentID, im.FromAgentID, 0, "Inworld inventory transfer declined", TransactionType.GiveInventory); } IScenePresence user = clientScene.GetScenePresence(im.ToAgentID); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(im); } } } }
void EventManager_OnSignificantClientMovement(IScenePresence presence) { if (Vector3.DistanceSquared(presence.AbsolutePosition, m_previousCheckedPosition) > 16*16) { m_previousCheckedPosition = presence.AbsolutePosition; SendTerrainUpdatesForClient(presence); } }
public bool TryGetScenePresence(UUID avatarId, out IScenePresence avatar) { return(m_sceneGraph.TryGetScenePresence(avatarId, out avatar)); }
public override bool TryGetPresenceValue(UUID key, out IScenePresence presence) { if (m_isChanging) { lock (m_changeLock) { return m_presenceEntities.TryGetValue(key, out presence); } } else return m_presenceEntities.TryGetValue(key, out presence); }
public bool TryGetAvatarByName(string avatarName, out IScenePresence avatar) { return(m_sceneGraph.TryGetAvatarByName(avatarName, out avatar)); }