From 99239ebcfcccd1a3fc1fa4360a33590eaa23c29a Mon Sep 17 00:00:00 2001 From: John Hurliman Date: Tue, 12 Aug 2008 22:38:02 +0000 Subject: [PATCH] * Splits libomv into OpenMetaverseTypes.dll and OpenMetaverse.dll * All MathUtils and non-SL-specific Helpers functions have been put in OpenMetaverseTypes.dll inside the Utils class. Helpers only contains SL-specific functions now * LLSD encoding/decoding for custom types has been moved out of the types and implemented as static functions in the LLSD class git-svn-id: http://libopenmetaverse.googlecode.com/svn/trunk@2082 52acb1d6-8a22-11de-b505-999d5b087335 --- OpenMetaverse.Rendering.GPL/GPLRenderer.cs | 60 +- OpenMetaverse.Tests/XmlLLSDTests.cs | 2 +- OpenMetaverse/AgentManager.cs | 110 ++-- OpenMetaverse/AppearanceManager.cs | 16 +- OpenMetaverse/AssetManager.cs | 2 +- OpenMetaverse/AssetTypes.cs | 14 +- OpenMetaverse/AvatarManager.cs | 54 +- OpenMetaverse/BitPack.cs | 2 +- OpenMetaverse/Capabilities/CapsBase.cs | 2 +- OpenMetaverse/Capabilities/CapsClient.cs | 48 +- .../Capabilities/EventQueueClient.cs | 49 +- OpenMetaverse/CapsToPacket.cs | 13 +- OpenMetaverse/DirectoryManager.cs | 46 +- OpenMetaverse/EstateTools.cs | 32 +- OpenMetaverse/GridManager.cs | 6 +- OpenMetaverse/GroupManager.cs | 56 +- OpenMetaverse/Helpers.cs | 497 +-------------- OpenMetaverse/InventoryManager.cs | 102 +-- OpenMetaverse/LLSD/BinaryLLSD.cs | 2 +- OpenMetaverse/LLSD/LLSD.cs | 158 ++++- OpenMetaverse/LLSD/NotationLLSD.cs | 8 +- OpenMetaverse/LLSD/XmlLLSD.cs | 14 +- OpenMetaverse/Login.cs | 12 +- OpenMetaverse/MathHelper.cs | 172 ----- OpenMetaverse/NameValue.cs | 10 +- OpenMetaverse/NetworkManager.cs | 4 +- OpenMetaverse/ObjectManager.cs | 24 +- OpenMetaverse/ParcelManager.cs | 44 +- OpenMetaverse/Prims.cs | 20 +- OpenMetaverse/Simulator.cs | 2 +- OpenMetaverse/TextureEntry.cs | 4 +- OpenMetaverse/Types/Color4.cs | 55 +- OpenMetaverse/Types/Matrix4.cs | 4 +- OpenMetaverse/Types/Quaternion.cs | 53 +- OpenMetaverse/Types/UUID.cs | 14 +- OpenMetaverse/Types/Utils.cs | 590 ++++++++++++++++++ OpenMetaverse/Types/Vector2.cs | 49 +- OpenMetaverse/Types/Vector3.cs | 57 +- OpenMetaverse/Types/Vector3d.cs | 57 +- OpenMetaverse/Types/Vector4.cs | 67 +- Programs/GridProxy/GridProxy.cs | 6 +- Programs/GridProxy/GridProxyLoader.cs | 4 +- Programs/GridProxy/Plugins/Analyst.cs | 6 +- Programs/GridProxy/Plugins/ClientAO.cs | 16 +- .../GridAccountant/frmGridAccountant.cs | 4 +- .../Commands/Groups/ActivateGroupCommand.cs | 2 +- .../Commands/Movement/FollowCommand.cs | 2 +- .../TestClient/Commands/System/MD5Command.cs | 2 +- Programs/examples/TestClient/TestClient.cs | 2 +- prebuild.xml | 53 +- 50 files changed, 1308 insertions(+), 1320 deletions(-) delete mode 100644 OpenMetaverse/MathHelper.cs create mode 100644 OpenMetaverse/Types/Utils.cs diff --git a/OpenMetaverse.Rendering.GPL/GPLRenderer.cs b/OpenMetaverse.Rendering.GPL/GPLRenderer.cs index 2414dd6c..0fc396fd 100644 --- a/OpenMetaverse.Rendering.GPL/GPLRenderer.cs +++ b/OpenMetaverse.Rendering.GPL/GPLRenderer.cs @@ -777,14 +777,14 @@ namespace OpenMetaverse.Rendering { PathPoint point = new PathPoint(); - float t = MathHelper.Lerp(prim.PathBegin, prim.PathEnd, (float)i * step); + float t = Utils.Lerp(prim.PathBegin, prim.PathEnd, (float)i * step); point.Position = new Vector3( - MathHelper.Lerp(0, prim.PathShearX, t), - MathHelper.Lerp(0, prim.PathShearY, t), + Utils.Lerp(0, prim.PathShearX, t), + Utils.Lerp(0, prim.PathShearY, t), t - 0.5f); - point.Rotation = Quaternion.CreateFromAxisAngle(MathHelper.Lerp(F_PI * prim.PathTwistBegin, F_PI * prim.PathTwist, t), 0f, 0f, 1f); - point.Scale.X = MathHelper.Lerp(startScale.X, endScale.X, t); - point.Scale.Y = MathHelper.Lerp(startScale.Y, endScale.Y, t); + point.Rotation = Quaternion.CreateFromAxisAngle(Utils.Lerp(F_PI * prim.PathTwistBegin, F_PI * prim.PathTwist, t), 0f, 0f, 1f); + point.Scale.X = Utils.Lerp(startScale.X, endScale.X, t); + point.Scale.Y = Utils.Lerp(startScale.Y, endScale.Y, t); point.TexT = t; path.Points.Add(point); @@ -860,7 +860,7 @@ namespace OpenMetaverse.Rendering angStep = 2f * F_PI * tStep * angScale; // Scale to have size "match" scale. Compensates to get object to generally fill bounding box - int totalSides = MathHelper.Round(sides / angScale); + int totalSides = Utils.Round(sides / angScale); if (totalSides < 8) scale = TABLE_SCALE[totalSides]; @@ -1030,21 +1030,21 @@ namespace OpenMetaverse.Rendering float step = 1f / sides; float t = prim.PathBegin; ang = 2f * F_PI * revolutions * t; - s = (float)Math.Sin(ang) * MathHelper.Lerp(radiusStart, radiusEnd, t); - c = (float)Math.Cos(ang) * MathHelper.Lerp(radiusStart, radiusEnd, t); + s = (float)Math.Sin(ang) * Utils.Lerp(radiusStart, radiusEnd, t); + c = (float)Math.Cos(ang) * Utils.Lerp(radiusStart, radiusEnd, t); point = new PathPoint(); point.Position = new Vector3( - 0 + MathHelper.Lerp(0, prim.PathShearX, s) + - 0 + MathHelper.Lerp(-skew, skew, t) * 0.5f, - c + MathHelper.Lerp(0, prim.PathShearY, s), + 0 + Utils.Lerp(0, prim.PathShearX, s) + + 0 + Utils.Lerp(-skew, skew, t) * 0.5f, + c + Utils.Lerp(0, prim.PathShearY, s), s); - point.Scale.X = holeX * MathHelper.Lerp(taperXBegin, taperXEnd, t); - point.Scale.Y = holeY * MathHelper.Lerp(taperYBegin, taperYEnd, t); + point.Scale.X = holeX * Utils.Lerp(taperXBegin, taperXEnd, t); + point.Scale.Y = holeY * Utils.Lerp(taperYBegin, taperYEnd, t); point.TexT = t; // Twist rotates the path along the x,y plane - twist = Quaternion.CreateFromAxisAngle(MathHelper.Lerp(twistBegin, twistEnd, t) * 2f * F_PI - F_PI, 0f, 0f, 1f); + twist = Quaternion.CreateFromAxisAngle(Utils.Lerp(twistBegin, twistEnd, t) * 2f * F_PI - F_PI, 0f, 0f, 1f); // Rotate the point around the circle's center qang = Quaternion.CreateFromAxisAngle(pathAxis, ang); point.Rotation = twist * qang; @@ -1061,21 +1061,21 @@ namespace OpenMetaverse.Rendering while (t < prim.PathEnd) { ang = 2f * F_PI * revolutions * t; - c = (float)Math.Cos(ang) * MathHelper.Lerp(radiusStart, radiusEnd, t); - s = (float)Math.Sin(ang) * MathHelper.Lerp(radiusStart, radiusEnd, t); + c = (float)Math.Cos(ang) * Utils.Lerp(radiusStart, radiusEnd, t); + s = (float)Math.Sin(ang) * Utils.Lerp(radiusStart, radiusEnd, t); point.Position = new Vector3( - 0 + MathHelper.Lerp(0, prim.PathShearX, s) + - 0 + MathHelper.Lerp(-skew, skew, t) * 0.5f, - c + MathHelper.Lerp(0, prim.PathShearY, s), + 0 + Utils.Lerp(0, prim.PathShearX, s) + + 0 + Utils.Lerp(-skew, skew, t) * 0.5f, + c + Utils.Lerp(0, prim.PathShearY, s), s); - point.Scale.X = holeX * MathHelper.Lerp(taperXBegin, taperXEnd, t); - point.Scale.Y = holeY * MathHelper.Lerp(taperYBegin, taperYEnd, t); + point.Scale.X = holeX * Utils.Lerp(taperXBegin, taperXEnd, t); + point.Scale.Y = holeY * Utils.Lerp(taperYBegin, taperYEnd, t); point.TexT = t; // Twist rotates the path along the x,y plane - twist = Quaternion.CreateFromAxisAngle(MathHelper.Lerp(twistBegin, twistEnd, t) * 2f * F_PI - F_PI, 0f, 0f, 1f); + twist = Quaternion.CreateFromAxisAngle(Utils.Lerp(twistBegin, twistEnd, t) * 2f * F_PI - F_PI, 0f, 0f, 1f); // Rotate the point around the circle's center qang = Quaternion.CreateFromAxisAngle(pathAxis, ang); point.Rotation = twist * qang; @@ -1088,19 +1088,19 @@ namespace OpenMetaverse.Rendering t = prim.PathEnd; point = new PathPoint(); ang = 2f * F_PI * revolutions * t; - c = (float)Math.Cos(ang) * MathHelper.Lerp(radiusStart, radiusEnd, t); - s = (float)Math.Sin(ang) * MathHelper.Lerp(radiusStart, radiusEnd, t); + c = (float)Math.Cos(ang) * Utils.Lerp(radiusStart, radiusEnd, t); + s = (float)Math.Sin(ang) * Utils.Lerp(radiusStart, radiusEnd, t); point.Position = new Vector3( - MathHelper.Lerp(0, prim.PathShearX, s) + MathHelper.Lerp(-skew, skew, t) * 0.5f, - c + MathHelper.Lerp(0, prim.PathShearY, s), + Utils.Lerp(0, prim.PathShearX, s) + Utils.Lerp(-skew, skew, t) * 0.5f, + c + Utils.Lerp(0, prim.PathShearY, s), s); - point.Scale.X = holeX * MathHelper.Lerp(taperXBegin, taperXEnd, t); - point.Scale.Y = holeY * MathHelper.Lerp(taperYBegin, taperYEnd, t); + point.Scale.X = holeX * Utils.Lerp(taperXBegin, taperXEnd, t); + point.Scale.Y = holeY * Utils.Lerp(taperYBegin, taperYEnd, t); point.TexT = t; // Twist rotates the path along the x,y plane - twist = Quaternion.CreateFromAxisAngle(MathHelper.Lerp(twistBegin, twistEnd, t) * 2f * F_PI - F_PI, 0f, 0f, 1f); + twist = Quaternion.CreateFromAxisAngle(Utils.Lerp(twistBegin, twistEnd, t) * 2f * F_PI - F_PI, 0f, 0f, 1f); qang = Quaternion.CreateFromAxisAngle(pathAxis, ang); point.Rotation = twist * qang; diff --git a/OpenMetaverse.Tests/XmlLLSDTests.cs b/OpenMetaverse.Tests/XmlLLSDTests.cs index 11d6304e..cd630d22 100644 --- a/OpenMetaverse.Tests/XmlLLSDTests.cs +++ b/OpenMetaverse.Tests/XmlLLSDTests.cs @@ -371,7 +371,7 @@ namespace OpenMetaverse.Tests Assert.AreEqual(LLSDType.Date, array[2].Type); tempDate = (LLSDDate)array[2]; - Assert.AreEqual(Helpers.Epoch, tempDate.AsDate()); + Assert.AreEqual(Utils.Epoch, tempDate.AsDate()); } /// diff --git a/OpenMetaverse/AgentManager.cs b/OpenMetaverse/AgentManager.cs index 1bbec9f7..ae0026ad 100644 --- a/OpenMetaverse/AgentManager.cs +++ b/OpenMetaverse/AgentManager.cs @@ -1216,7 +1216,7 @@ namespace OpenMetaverse chat.AgentData.AgentID = this.id; chat.AgentData.SessionID = Client.Self.SessionID; chat.ChatData.Channel = channel; - chat.ChatData.Message = Helpers.StringToField(message); + chat.ChatData.Message = Utils.StringToBytes(message); chat.ChatData.Type = (byte)type; Client.Network.SendPacket(chat); @@ -1312,10 +1312,10 @@ namespace OpenMetaverse im.AgentData.SessionID = Client.Self.SessionID; im.MessageBlock.Dialog = (byte)dialog; - im.MessageBlock.FromAgentName = Helpers.StringToField(fromName); + im.MessageBlock.FromAgentName = Utils.StringToBytes(fromName); im.MessageBlock.FromGroup = false; im.MessageBlock.ID = imSessionID; - im.MessageBlock.Message = Helpers.StringToField(message); + im.MessageBlock.Message = Utils.StringToBytes(message); im.MessageBlock.Offline = (byte)offline; im.MessageBlock.ToAgentID = target; @@ -1366,15 +1366,15 @@ namespace OpenMetaverse im.AgentData.AgentID = Client.Self.AgentID; im.AgentData.SessionID = Client.Self.SessionID; im.MessageBlock.Dialog = (byte)InstantMessageDialog.SessionSend; - im.MessageBlock.FromAgentName = Helpers.StringToField(fromName); + im.MessageBlock.FromAgentName = Utils.StringToBytes(fromName); im.MessageBlock.FromGroup = false; - im.MessageBlock.Message = Helpers.StringToField(message); + im.MessageBlock.Message = Utils.StringToBytes(message); im.MessageBlock.Offline = 0; im.MessageBlock.ID = groupID; im.MessageBlock.ToAgentID = groupID; im.MessageBlock.Position = Vector3.Zero; im.MessageBlock.RegionID = UUID.Zero; - im.MessageBlock.BinaryBucket = Helpers.StringToField("\0"); + im.MessageBlock.BinaryBucket = Utils.StringToBytes("\0"); Client.Network.SendPacket(im); } @@ -1396,7 +1396,7 @@ namespace OpenMetaverse im.AgentData.AgentID = Client.Self.AgentID; im.AgentData.SessionID = Client.Self.SessionID; im.MessageBlock.Dialog = (byte)InstantMessageDialog.SessionGroupStart; - im.MessageBlock.FromAgentName = Helpers.StringToField(Client.Self.Name); + im.MessageBlock.FromAgentName = Utils.StringToBytes(Client.Self.Name); im.MessageBlock.FromGroup = false; im.MessageBlock.Message = new byte[0]; im.MessageBlock.Offline = 0; @@ -1420,7 +1420,7 @@ namespace OpenMetaverse im.AgentData.AgentID = Client.Self.AgentID; im.AgentData.SessionID = Client.Self.SessionID; im.MessageBlock.Dialog = (byte)InstantMessageDialog.SessionDrop; - im.MessageBlock.FromAgentName = Helpers.StringToField(Client.Self.Name); + im.MessageBlock.FromAgentName = Utils.StringToBytes(Client.Self.Name); im.MessageBlock.FromGroup = false; im.MessageBlock.Message = new byte[0]; im.MessageBlock.Offline = 0; @@ -1449,7 +1449,7 @@ namespace OpenMetaverse reply.AgentData.SessionID = Client.Self.SessionID; reply.Data.ButtonIndex = buttonIndex; - reply.Data.ButtonLabel = Helpers.StringToField(buttonlabel); + reply.Data.ButtonLabel = Utils.StringToBytes(buttonlabel); reply.Data.ChatChannel = channel; reply.Data.ObjectID = objectID; @@ -1711,14 +1711,14 @@ namespace OpenMetaverse autopilot.AgentData.SessionID = Client.Self.SessionID; autopilot.AgentData.TransactionID = UUID.Zero; autopilot.MethodData.Invoice = UUID.Zero; - autopilot.MethodData.Method = Helpers.StringToField("autopilot"); + autopilot.MethodData.Method = Utils.StringToBytes("autopilot"); autopilot.ParamList = new GenericMessagePacket.ParamListBlock[3]; autopilot.ParamList[0] = new GenericMessagePacket.ParamListBlock(); - autopilot.ParamList[0].Parameter = Helpers.StringToField(globalX.ToString()); + autopilot.ParamList[0].Parameter = Utils.StringToBytes(globalX.ToString()); autopilot.ParamList[1] = new GenericMessagePacket.ParamListBlock(); - autopilot.ParamList[1].Parameter = Helpers.StringToField(globalY.ToString()); + autopilot.ParamList[1].Parameter = Utils.StringToBytes(globalY.ToString()); autopilot.ParamList[2] = new GenericMessagePacket.ParamListBlock(); - autopilot.ParamList[2].Parameter = Helpers.StringToField(z.ToString()); + autopilot.ParamList[2].Parameter = Utils.StringToBytes(z.ToString()); Client.Network.SendPacket(autopilot); } @@ -1738,14 +1738,14 @@ namespace OpenMetaverse autopilot.AgentData.SessionID = Client.Self.SessionID; autopilot.AgentData.TransactionID = UUID.Zero; autopilot.MethodData.Invoice = UUID.Zero; - autopilot.MethodData.Method = Helpers.StringToField("autopilot"); + autopilot.MethodData.Method = Utils.StringToBytes("autopilot"); autopilot.ParamList = new GenericMessagePacket.ParamListBlock[3]; autopilot.ParamList[0] = new GenericMessagePacket.ParamListBlock(); - autopilot.ParamList[0].Parameter = Helpers.StringToField(globalX.ToString()); + autopilot.ParamList[0].Parameter = Utils.StringToBytes(globalX.ToString()); autopilot.ParamList[1] = new GenericMessagePacket.ParamListBlock(); - autopilot.ParamList[1].Parameter = Helpers.StringToField(globalY.ToString()); + autopilot.ParamList[1].Parameter = Utils.StringToBytes(globalY.ToString()); autopilot.ParamList[2] = new GenericMessagePacket.ParamListBlock(); - autopilot.ParamList[2].Parameter = Helpers.StringToField(z.ToString()); + autopilot.ParamList[2].Parameter = Utils.StringToBytes(z.ToString()); Client.Network.SendPacket(autopilot); } @@ -1951,7 +1951,7 @@ namespace OpenMetaverse MoneyTransferRequestPacket money = new MoneyTransferRequestPacket(); money.AgentData.AgentID = this.id; money.AgentData.SessionID = Client.Self.SessionID; - money.MoneyData.Description = Helpers.StringToField(description); + money.MoneyData.Description = Utils.StringToBytes(description); money.MoneyData.DestID = target; money.MoneyData.SourceID = this.id; money.MoneyData.TransactionType = (int)type; @@ -2229,7 +2229,7 @@ namespace OpenMetaverse p.AgentData.AgentID = Client.Self.id; p.AgentData.SessionID = Client.Self.SessionID; p.Info.LureType = 0; - p.Info.Message = Helpers.StringToField(message); + p.Info.Message = Utils.StringToBytes(message); p.TargetData = new StartLurePacket.TargetDataBlock[] { new StartLurePacket.TargetDataBlock() }; p.TargetData[0].TargetID = targetID; Client.Network.SendPacket(p); @@ -2274,13 +2274,13 @@ namespace OpenMetaverse AvatarPropertiesUpdatePacket apup = new AvatarPropertiesUpdatePacket(); apup.AgentData.AgentID = id; apup.AgentData.SessionID = sessionID; - apup.PropertiesData.AboutText = Helpers.StringToField(profile.AboutText); + apup.PropertiesData.AboutText = Utils.StringToBytes(profile.AboutText); apup.PropertiesData.AllowPublish = profile.AllowPublish; - apup.PropertiesData.FLAboutText = Helpers.StringToField(profile.FirstLifeText); + apup.PropertiesData.FLAboutText = Utils.StringToBytes(profile.FirstLifeText); apup.PropertiesData.FLImageID = profile.FirstLifeImage; apup.PropertiesData.ImageID = profile.ProfileImage; apup.PropertiesData.MaturePublish = profile.MaturePublish; - apup.PropertiesData.ProfileURL = Helpers.StringToField(profile.ProfileURL); + apup.PropertiesData.ProfileURL = Utils.StringToBytes(profile.ProfileURL); Client.Network.SendPacket(apup); } @@ -2294,11 +2294,11 @@ namespace OpenMetaverse AvatarInterestsUpdatePacket aiup = new AvatarInterestsUpdatePacket(); aiup.AgentData.AgentID = id; aiup.AgentData.SessionID = sessionID; - aiup.PropertiesData.LanguagesText = Helpers.StringToField(interests.LanguagesText); + aiup.PropertiesData.LanguagesText = Utils.StringToBytes(interests.LanguagesText); aiup.PropertiesData.SkillsMask = interests.SkillsMask; - aiup.PropertiesData.SkillsText = Helpers.StringToField(interests.SkillsText); + aiup.PropertiesData.SkillsText = Utils.StringToBytes(interests.SkillsText); aiup.PropertiesData.WantToMask = interests.WantToMask; - aiup.PropertiesData.WantToText = Helpers.StringToField(interests.WantToText); + aiup.PropertiesData.WantToText = Utils.StringToBytes(interests.WantToText); Client.Network.SendPacket(aiup); } @@ -2349,7 +2349,7 @@ namespace OpenMetaverse s.StartLocationData = new SetStartLocationRequestPacket.StartLocationDataBlock(); s.StartLocationData.LocationPos = Client.Self.SimPosition; s.StartLocationData.LocationID = 1; - s.StartLocationData.SimName = Helpers.StringToField(String.Empty); + s.StartLocationData.SimName = Utils.StringToBytes(String.Empty); s.StartLocationData.LocationLookAt = Movement.Camera.AtAxis; Client.Network.SendPacket(s); } @@ -2421,7 +2421,7 @@ namespace OpenMetaverse request.Requester.RequestID = requestID; request.Requester.SearchDir = Quaternion.Identity; // TODO: this needs to be tested request.Requester.SearchID = searchID; - request.Requester.SearchName = Helpers.StringToField(name); + request.Requester.SearchName = Utils.StringToBytes(name); request.Requester.SearchPos = Vector3.Zero; request.Requester.SearchRegions = 0; // TODO: ? request.Requester.SourceID = Client.Self.AgentID; @@ -2449,7 +2449,7 @@ namespace OpenMetaverse { InstantMessage message; message.FromAgentID = im.AgentData.AgentID; - message.FromAgentName = Helpers.FieldToUTF8String(im.MessageBlock.FromAgentName); + message.FromAgentName = Utils.BytesToString(im.MessageBlock.FromAgentName); message.ToAgentID = im.MessageBlock.ToAgentID; message.ParentEstateID = im.MessageBlock.ParentEstateID; message.RegionID = im.MessageBlock.RegionID; @@ -2458,7 +2458,7 @@ namespace OpenMetaverse message.GroupIM = im.MessageBlock.FromGroup; message.IMSessionID = im.MessageBlock.ID; message.Timestamp = new DateTime(im.MessageBlock.Timestamp); - message.Message = Helpers.FieldToUTF8String(im.MessageBlock.Message); + message.Message = Utils.BytesToString(im.MessageBlock.Message); message.Offline = (InstantMessageOnline)im.MessageBlock.Offline; message.BinaryBucket = im.MessageBlock.BinaryBucket; @@ -2480,11 +2480,11 @@ namespace OpenMetaverse { ChatFromSimulatorPacket chat = (ChatFromSimulatorPacket)packet; - OnChat(Helpers.FieldToUTF8String(chat.ChatData.Message) + OnChat(Utils.BytesToString(chat.ChatData.Message) , (ChatAudibleLevel)chat.ChatData.Audible , (ChatType)chat.ChatData.ChatType , (ChatSourceType)chat.ChatData.SourceType - , Helpers.FieldToUTF8String(chat.ChatData.FromName) + , Utils.BytesToString(chat.ChatData.FromName) , chat.ChatData.SourceID , chat.ChatData.OwnerID , chat.ChatData.Position @@ -2506,15 +2506,15 @@ namespace OpenMetaverse foreach (ScriptDialogPacket.ButtonsBlock button in dialog.Buttons) { - buttons.Add(Helpers.FieldToUTF8String(button.ButtonLabel)); + buttons.Add(Utils.BytesToString(button.ButtonLabel)); } - OnScriptDialog(Helpers.FieldToUTF8String(dialog.Data.Message), - Helpers.FieldToUTF8String(dialog.Data.ObjectName), + OnScriptDialog(Utils.BytesToString(dialog.Data.Message), + Utils.BytesToString(dialog.Data.ObjectName), dialog.Data.ImageID, dialog.Data.ObjectID, - Helpers.FieldToUTF8String(dialog.Data.FirstName), - Helpers.FieldToUTF8String(dialog.Data.LastName), + Utils.BytesToString(dialog.Data.FirstName), + Utils.BytesToString(dialog.Data.LastName), dialog.Data.ChatChannel, buttons); } @@ -2536,8 +2536,8 @@ namespace OpenMetaverse OnScriptQuestion(simulator, question.Data.TaskID, question.Data.ItemID, - Helpers.FieldToUTF8String(question.Data.ObjectName), - Helpers.FieldToUTF8String(question.Data.ObjectOwner), + Utils.BytesToString(question.Data.ObjectName), + Utils.BytesToString(question.Data.ObjectOwner), (ScriptPermission)question.Data.Questions); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } @@ -2579,12 +2579,12 @@ namespace OpenMetaverse { try { OnLoadURL( - Helpers.FieldToUTF8String(loadURL.Data.ObjectName), + Utils.BytesToString(loadURL.Data.ObjectName), loadURL.Data.ObjectID, loadURL.Data.OwnerID, loadURL.Data.OwnerIsGroup, - Helpers.FieldToUTF8String(loadURL.Data.Message), - Helpers.FieldToUTF8String(loadURL.Data.URL) + Utils.BytesToString(loadURL.Data.Message), + Utils.BytesToString(loadURL.Data.URL) ); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } @@ -2604,7 +2604,7 @@ namespace OpenMetaverse relativePosition = movement.Data.Position; Movement.Camera.LookDirection(movement.Data.LookAt); simulator.Handle = movement.Data.RegionHandle; - simulator.SimVersion = Helpers.FieldToUTF8String(movement.SimData.ChannelVersion); + simulator.SimVersion = Utils.BytesToString(movement.SimData.ChannelVersion); } /// @@ -2623,14 +2623,14 @@ namespace OpenMetaverse if (p.AgentData.AgentID == simulator.Client.Self.AgentID) { - firstName = Helpers.FieldToUTF8String(p.AgentData.FirstName); - lastName = Helpers.FieldToUTF8String(p.AgentData.LastName); + firstName = Utils.BytesToString(p.AgentData.FirstName); + lastName = Utils.BytesToString(p.AgentData.LastName); activeGroup = p.AgentData.ActiveGroupID; if (OnAgentDataUpdated != null) { - string groupTitle = Helpers.FieldToUTF8String(p.AgentData.GroupTitle); - string groupName = Helpers.FieldToUTF8String(p.AgentData.GroupName); + string groupTitle = Utils.BytesToString(p.AgentData.GroupTitle); + string groupName = Utils.BytesToString(p.AgentData.GroupName); try { OnAgentDataUpdated(firstName, lastName, activeGroup, groupTitle, (GroupPowers)p.AgentData.GroupPowers, groupName); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } @@ -2660,7 +2660,7 @@ namespace OpenMetaverse try { OnMoneyBalanceReplyReceived(mbrp.MoneyData.TransactionID, mbrp.MoneyData.TransactionSuccess, mbrp.MoneyData.MoneyBalance, mbrp.MoneyData.SquareMetersCredit, mbrp.MoneyData.SquareMetersCommitted, - Helpers.FieldToUTF8String(mbrp.MoneyData.Description)); } + Utils.BytesToString(mbrp.MoneyData.Description)); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } @@ -2725,7 +2725,7 @@ namespace OpenMetaverse { TeleportProgressPacket progress = (TeleportProgressPacket)packet; - teleportMessage = Helpers.FieldToUTF8String(progress.Info.Message); + teleportMessage = Utils.BytesToString(progress.Info.Message); flags = (TeleportFlags)progress.Info.TeleportFlags; teleportStat = TeleportStatus.Progress; @@ -2735,7 +2735,7 @@ namespace OpenMetaverse { TeleportFailedPacket failed = (TeleportFailedPacket)packet; - teleportMessage = Helpers.FieldToUTF8String(failed.Info.Reason); + teleportMessage = Utils.BytesToString(failed.Info.Reason); teleportStat = TeleportStatus.Failed; finished = true; @@ -2746,7 +2746,7 @@ namespace OpenMetaverse TeleportFinishPacket finish = (TeleportFinishPacket)packet; flags = (TeleportFlags)finish.Info.TeleportFlags; - string seedcaps = Helpers.FieldToUTF8String(finish.Info.SeedCapability); + string seedcaps = Utils.BytesToString(finish.Info.SeedCapability); finished = true; Logger.DebugLog("TeleportFinish received, Flags: " + flags.ToString(), Client); @@ -2879,7 +2879,7 @@ namespace OpenMetaverse { MeanCollisionAlertPacket.MeanCollisionBlock block = collision.MeanCollision[i]; - DateTime time = Helpers.UnixTimeToDateTime(block.Time); + DateTime time = Utils.UnixTimeToDateTime(block.Time); MeanCollisionType type = (MeanCollisionType)block.Type; try { OnMeanCollision(type, block.Perp, block.Victim, block.Mag, time); } @@ -2918,7 +2918,7 @@ namespace OpenMetaverse private void CrossedRegionHandler(Packet packet, Simulator sim) { CrossedRegionPacket crossing = (CrossedRegionPacket)packet; - string seedCap = Helpers.FieldToUTF8String(crossing.RegionData.SeedCapability); + string seedCap = Utils.BytesToString(crossing.RegionData.SeedCapability); IPEndPoint endPoint = new IPEndPoint(crossing.RegionData.SimIP, crossing.RegionData.SimPort); Logger.DebugLog("Crossed in to new region area, attempting to connect to " + endPoint.ToString(), Client); @@ -3064,7 +3064,7 @@ namespace OpenMetaverse message.ToAgentID = msg["to_id"].AsString(); message.ParentEstateID = (uint)msg["parent_estate_id"].AsInteger(); message.RegionID = msg["region_id"].AsUUID(); - message.Position.FromLLSD(msg["position"]); + message.Position = ((LLSDArray)msg["position"]).AsVector3(); message.Dialog = (InstantMessageDialog)msgdata["type"].AsInteger(); message.GroupIM = true; message.IMSessionID = map["session_id"].AsUUID(); @@ -3086,7 +3086,7 @@ namespace OpenMetaverse private void AlertMessageHandler(Packet packet, Simulator simulator) { AlertMessagePacket alert = (AlertMessagePacket)packet; - string message = Helpers.FieldToUTF8String(alert.AlertData.Message); + string message = Utils.BytesToString(alert.AlertData.Message); if (OnAlertMessage != null) { @@ -3127,7 +3127,7 @@ namespace OpenMetaverse ScriptSensorReplyPacket.SensedDataBlock block = reply.SensedData[i]; ScriptSensorReplyPacket.RequesterBlock requestor = reply.Requester; - try { OnScriptSensorReply(requestor.SourceID, block.GroupID, Helpers.FieldToUTF8String(block.Name), + try { OnScriptSensorReply(requestor.SourceID, block.GroupID, Utils.BytesToString(block.Name), block.ObjectID, block.OwnerID, block.Position, block.Range, block.Rotation, (ScriptSensorTypeFlags)block.Type, block.Velocity); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } diff --git a/OpenMetaverse/AppearanceManager.cs b/OpenMetaverse/AppearanceManager.cs index 749504ed..f5f9589d 100644 --- a/OpenMetaverse/AppearanceManager.cs +++ b/OpenMetaverse/AppearanceManager.cs @@ -514,8 +514,8 @@ namespace OpenMetaverse attachmentsPacket.ObjectData[i].GroupMask = (uint)attachment.Permissions.GroupMask; attachmentsPacket.ObjectData[i].ItemFlags = (uint)attachment.Flags; attachmentsPacket.ObjectData[i].ItemID = attachment.UUID; - attachmentsPacket.ObjectData[i].Name = Helpers.StringToField(attachment.Name); - attachmentsPacket.ObjectData[i].Description = Helpers.StringToField(attachment.Description); + attachmentsPacket.ObjectData[i].Name = Utils.StringToBytes(attachment.Name); + attachmentsPacket.ObjectData[i].Description = Utils.StringToBytes(attachment.Description); attachmentsPacket.ObjectData[i].NextOwnerMask = (uint)attachment.Permissions.NextOwnerMask; attachmentsPacket.ObjectData[i].OwnerID = attachment.OwnerID; } @@ -528,8 +528,8 @@ namespace OpenMetaverse attachmentsPacket.ObjectData[i].GroupMask = (uint)attachment.Permissions.GroupMask; attachmentsPacket.ObjectData[i].ItemFlags = (uint)attachment.Flags; attachmentsPacket.ObjectData[i].ItemID = attachment.UUID; - attachmentsPacket.ObjectData[i].Name = Helpers.StringToField(attachment.Name); - attachmentsPacket.ObjectData[i].Description = Helpers.StringToField(attachment.Description); + attachmentsPacket.ObjectData[i].Name = Utils.StringToBytes(attachment.Name); + attachmentsPacket.ObjectData[i].Description = Utils.StringToBytes(attachment.Description); attachmentsPacket.ObjectData[i].NextOwnerMask = (uint)attachment.Permissions.NextOwnerMask; attachmentsPacket.ObjectData[i].OwnerID = attachment.OwnerID; } @@ -578,12 +578,12 @@ namespace OpenMetaverse attach.AgentData.SessionID = Client.Self.SessionID; attach.ObjectData.AttachmentPt = (byte)attachPoint; - attach.ObjectData.Description = Helpers.StringToField(description); + attach.ObjectData.Description = Utils.StringToBytes(description); attach.ObjectData.EveryoneMask = (uint)perms.EveryoneMask; attach.ObjectData.GroupMask = (uint)perms.GroupMask; attach.ObjectData.ItemFlags = itemFlags; attach.ObjectData.ItemID = itemID; - attach.ObjectData.Name = Helpers.StringToField(name); + attach.ObjectData.Name = Utils.StringToBytes(name); attach.ObjectData.NextOwnerMask = (uint)perms.NextOwnerMask; attach.ObjectData.OwnerID = ownerID; @@ -1117,7 +1117,7 @@ namespace OpenMetaverse block.TextureID.ToString(), Client); // FIXME: Use this. Right now we treat baked images on other sims as if they were missing - string host = Helpers.FieldToUTF8String(block.HostName); + string host = Utils.BytesToString(block.HostName); if (host.Length > 0) Logger.DebugLog("Cached bake exists on foreign host " + host, Client); BakeType bakeType = (BakeType)block.TextureIndex; @@ -1246,7 +1246,7 @@ namespace OpenMetaverse if (!kvp.Value.Asset.Decode()) { Logger.Log("Failed to decode asset:" + Environment.NewLine + - Helpers.FieldToUTF8String(asset.AssetData), Helpers.LogLevel.Error, Client); + Utils.BytesToString(asset.AssetData), Helpers.LogLevel.Error, Client); } lock (AgentTextures) diff --git a/OpenMetaverse/AssetManager.cs b/OpenMetaverse/AssetManager.cs index 04431f3f..2931c461 100644 --- a/OpenMetaverse/AssetManager.cs +++ b/OpenMetaverse/AssetManager.cs @@ -497,7 +497,7 @@ namespace OpenMetaverse RequestXferPacket request = new RequestXferPacket(); request.XferID.ID = id; - request.XferID.Filename = Helpers.StringToField(filename); + request.XferID.Filename = Utils.StringToBytes(filename); request.XferID.FilePath = 4; // "Cache". This is a horrible thing that hardcodes a file path enumeration in to the // protocol. For asset downloads we should only ever need this value request.XferID.DeleteOnCompletion = deleteOnCompletion; diff --git a/OpenMetaverse/AssetTypes.cs b/OpenMetaverse/AssetTypes.cs index 501fa0e3..3425a47a 100644 --- a/OpenMetaverse/AssetTypes.cs +++ b/OpenMetaverse/AssetTypes.cs @@ -159,12 +159,12 @@ namespace OpenMetaverse temp += Text.Length + "\n"; temp += Text; temp += "}"; - AssetData = Helpers.StringToField(temp); + AssetData = Utils.StringToBytes(temp); } public override bool Decode() { - Text = Helpers.FieldToUTF8String(AssetData); + Text = Utils.BytesToString(AssetData); return true; } } @@ -186,12 +186,12 @@ namespace OpenMetaverse public override void Encode() { - AssetData = Helpers.StringToField(Source); + AssetData = Utils.StringToBytes(Source); } public override bool Decode() { - Source = Helpers.FieldToUTF8String(AssetData); + Source = Utils.BytesToString(AssetData); return true; } } @@ -299,14 +299,14 @@ namespace OpenMetaverse public AssetWearable(string source) { - AssetData = Helpers.StringToField(source); + AssetData = Utils.StringToBytes(source); } public override bool Decode() { int version = -1; Permissions = new Permissions(); - string data = Helpers.FieldToUTF8String(AssetData); + string data = Utils.BytesToString(AssetData); string[] lines = data.Split('\n'); for (int stri = 0; stri < lines.Length; stri++) @@ -470,7 +470,7 @@ namespace OpenMetaverse data.Append(texture.Key); data.Append(" "); data.Append(texture.Value.ToString()); data.Append(NL); } - AssetData = Helpers.StringToField(data.ToString()); + AssetData = Utils.StringToBytes(data.ToString()); } } diff --git a/OpenMetaverse/AvatarManager.cs b/OpenMetaverse/AvatarManager.cs index 03ee562f..f6f1ecad 100644 --- a/OpenMetaverse/AvatarManager.cs +++ b/OpenMetaverse/AvatarManager.cs @@ -292,7 +292,7 @@ namespace OpenMetaverse aprp.AgentData.AgentID = Client.Self.AgentID; aprp.AgentData.SessionID = Client.Self.SessionID; aprp.AgentData.QueryID = queryID; - aprp.Data.Name = Helpers.StringToField(name); + aprp.Data.Name = Utils.StringToBytes(name); Client.Network.SendPacket(aprp); } @@ -309,11 +309,11 @@ namespace OpenMetaverse gmp.AgentData.SessionID = Client.Self.SessionID; gmp.AgentData.TransactionID = UUID.Zero; - gmp.MethodData.Method = Helpers.StringToField("avatarpicksrequest"); + gmp.MethodData.Method = Utils.StringToBytes("avatarpicksrequest"); gmp.MethodData.Invoice = UUID.Zero; gmp.ParamList = new GenericMessagePacket.ParamListBlock[1]; gmp.ParamList[0] = new GenericMessagePacket.ParamListBlock(); - gmp.ParamList[0].Parameter = Helpers.StringToField(avatarid.ToString()); + gmp.ParamList[0].Parameter = Utils.StringToBytes(avatarid.ToString()); Client.Network.SendPacket(gmp); } @@ -331,13 +331,13 @@ namespace OpenMetaverse gmp.AgentData.SessionID = Client.Self.SessionID; gmp.AgentData.TransactionID = UUID.Zero; - gmp.MethodData.Method = Helpers.StringToField("pickinforequest"); + gmp.MethodData.Method = Utils.StringToBytes("pickinforequest"); gmp.MethodData.Invoice = UUID.Zero; gmp.ParamList = new GenericMessagePacket.ParamListBlock[2]; gmp.ParamList[0] = new GenericMessagePacket.ParamListBlock(); - gmp.ParamList[0].Parameter = Helpers.StringToField(avatarid.ToString()); + gmp.ParamList[0].Parameter = Utils.StringToBytes(avatarid.ToString()); gmp.ParamList[1] = new GenericMessagePacket.ParamListBlock(); - gmp.ParamList[1].Parameter = Helpers.StringToField(pickid.ToString()); + gmp.ParamList[1].Parameter = Utils.StringToBytes(pickid.ToString()); Client.Network.SendPacket(gmp); } @@ -358,8 +358,8 @@ namespace OpenMetaverse foreach (UUIDNameReplyPacket.UUIDNameBlockBlock block in reply.UUIDNameBlock) { - names[block.ID] = Helpers.FieldToUTF8String(block.FirstName) + - " " + Helpers.FieldToUTF8String(block.LastName); + names[block.ID] = Utils.BytesToString(block.FirstName) + + " " + Utils.BytesToString(block.LastName); } OnAvatarNames(names); @@ -414,10 +414,10 @@ namespace OpenMetaverse properties.ProfileImage = reply.PropertiesData.ImageID; properties.FirstLifeImage = reply.PropertiesData.FLImageID; properties.Partner = reply.PropertiesData.PartnerID; - properties.AboutText = Helpers.FieldToUTF8String(reply.PropertiesData.AboutText); - properties.FirstLifeText = Helpers.FieldToUTF8String(reply.PropertiesData.FLAboutText); - properties.BornOn = Helpers.FieldToUTF8String(reply.PropertiesData.BornOn); - //properties.CharterMember = Helpers.FieldToUTF8String(reply.PropertiesData.CharterMember); + properties.AboutText = Utils.BytesToString(reply.PropertiesData.AboutText); + properties.FirstLifeText = Utils.BytesToString(reply.PropertiesData.FLAboutText); + properties.BornOn = Utils.BytesToString(reply.PropertiesData.BornOn); + //properties.CharterMember = Utils.BytesToString(reply.PropertiesData.CharterMember); uint charter = Helpers.BytesToUInt(reply.PropertiesData.CharterMember); if ( charter == 0 ) { properties.CharterMember = "Resident"; @@ -426,10 +426,10 @@ namespace OpenMetaverse } else if ( charter == 3 ) { properties.CharterMember = "Linden"; } else { - properties.CharterMember = Helpers.FieldToUTF8String(reply.PropertiesData.CharterMember); + properties.CharterMember = Utils.BytesToString(reply.PropertiesData.CharterMember); } properties.Flags = (Avatar.ProfileFlags)reply.PropertiesData.Flags; - properties.ProfileURL = Helpers.FieldToUTF8String(reply.PropertiesData.ProfileURL); + properties.ProfileURL = Utils.BytesToString(reply.PropertiesData.ProfileURL); OnAvatarProperties(reply.AgentData.AvatarID, properties); } @@ -446,10 +446,10 @@ namespace OpenMetaverse Avatar.Interests interests = new Avatar.Interests(); interests.WantToMask = airp.PropertiesData.WantToMask; - interests.WantToText = Helpers.FieldToUTF8String(airp.PropertiesData.WantToText); + interests.WantToText = Utils.BytesToString(airp.PropertiesData.WantToText); interests.SkillsMask = airp.PropertiesData.SkillsMask; - interests.SkillsText = Helpers.FieldToUTF8String(airp.PropertiesData.SkillsText); - interests.LanguagesText = Helpers.FieldToUTF8String(airp.PropertiesData.LanguagesText); + interests.SkillsText = Utils.BytesToString(airp.PropertiesData.SkillsText); + interests.LanguagesText = Utils.BytesToString(airp.PropertiesData.LanguagesText); OnAvatarInterests(airp.AgentData.AvatarID, interests); } @@ -470,9 +470,9 @@ namespace OpenMetaverse avatarGroup.AcceptNotices = groups.GroupData[i].AcceptNotices; avatarGroup.GroupID = groups.GroupData[i].GroupID; avatarGroup.GroupInsigniaID = groups.GroupData[i].GroupInsigniaID; - avatarGroup.GroupName = Helpers.FieldToUTF8String(groups.GroupData[i].GroupName); + avatarGroup.GroupName = Utils.BytesToString(groups.GroupData[i].GroupName); avatarGroup.GroupPowers = (GroupPowers)groups.GroupData[i].GroupPowers; - avatarGroup.GroupTitle = Helpers.FieldToUTF8String(groups.GroupData[i].GroupTitle); + avatarGroup.GroupTitle = Utils.BytesToString(groups.GroupData[i].GroupTitle); avatarGroup.ListInProfile = groups.NewGroupData.ListInProfile; avatarGroups.Add(avatarGroup); @@ -492,8 +492,8 @@ namespace OpenMetaverse foreach (AvatarPickerReplyPacket.DataBlock block in reply.Data) { - avatars[block.AvatarID] = Helpers.FieldToUTF8String(block.FirstName) + - " " + Helpers.FieldToUTF8String(block.LastName); + avatars[block.AvatarID] = Utils.BytesToString(block.FirstName) + + " " + Utils.BytesToString(block.LastName); } try { OnAvatarNameSearch(reply.AgentData.QueryID, avatars); } @@ -645,7 +645,7 @@ namespace OpenMetaverse Dictionary picks = new Dictionary(); foreach (AvatarPicksReplyPacket.DataBlock b in p.Data) { - picks.Add(b.PickID, Helpers.FieldToUTF8String(b.PickName)); + picks.Add(b.PickID, Utils.BytesToString(b.PickName)); } try { @@ -667,18 +667,18 @@ namespace OpenMetaverse PickInfoReplyPacket p = (PickInfoReplyPacket)packet; ProfilePick ret = new ProfilePick(); ret.CreatorID = p.Data.CreatorID; - ret.Desc = Helpers.FieldToUTF8String(p.Data.Desc); + ret.Desc = Utils.BytesToString(p.Data.Desc); ret.Enabled = p.Data.Enabled; - ret.Name = Helpers.FieldToUTF8String(p.Data.Name); - ret.OriginalName = Helpers.FieldToUTF8String(p.Data.OriginalName); + ret.Name = Utils.BytesToString(p.Data.Name); + ret.OriginalName = Utils.BytesToString(p.Data.OriginalName); ret.ParcelID = p.Data.ParcelID; ret.PickID = p.Data.PickID; ret.PosGlobal = p.Data.PosGlobal; - ret.SimName = Helpers.FieldToUTF8String(p.Data.SimName); + ret.SimName = Utils.BytesToString(p.Data.SimName); ret.SnapshotID = p.Data.SnapshotID; ret.SortOrder = p.Data.SortOrder; ret.TopPick = p.Data.TopPick; - ret.User = Helpers.FieldToUTF8String(p.Data.User); + ret.User = Utils.BytesToString(p.Data.User); try { OnPickInfo(ret.PickID, ret); diff --git a/OpenMetaverse/BitPack.cs b/OpenMetaverse/BitPack.cs index 0a9b2b19..fc1079b3 100644 --- a/OpenMetaverse/BitPack.cs +++ b/OpenMetaverse/BitPack.cs @@ -134,7 +134,7 @@ namespace OpenMetaverse max = 1 << intBits; - float fixedVal = MathHelper.Clamp(data, (float)min, (float)max); + float fixedVal = Utils.Clamp(data, (float)min, (float)max); if (isSigned) fixedVal += max; fixedVal *= 1 << fracBits; diff --git a/OpenMetaverse/Capabilities/CapsBase.cs b/OpenMetaverse/Capabilities/CapsBase.cs index 82d7b743..33743285 100644 --- a/OpenMetaverse/Capabilities/CapsBase.cs +++ b/OpenMetaverse/Capabilities/CapsBase.cs @@ -451,7 +451,7 @@ namespace OpenMetaverse.Capabilities // The Linden Lab event queue server breaks HTTP 1.1 by always replying with a // Connection: Close header, which will confuse the Windows .NET runtime and throw // a "Connection unexpectedly closed" exception. This is our cross-platform hack - if (Helpers.GetRunningRuntime() == Helpers.Runtime.Mono) + if (Utils.GetRunningRuntime() == Utils.Runtime.Mono) uploadDataRequest.KeepAlive = true; try diff --git a/OpenMetaverse/Capabilities/CapsClient.cs b/OpenMetaverse/Capabilities/CapsClient.cs index b4291da4..9deb36c2 100644 --- a/OpenMetaverse/Capabilities/CapsClient.cs +++ b/OpenMetaverse/Capabilities/CapsClient.cs @@ -144,14 +144,31 @@ namespace OpenMetaverse.Capabilities } else { - if (Helpers.StringContains(e.Error.Message, "502")) + // Some error occurred, try to figure out what happened + HttpStatusCode code = HttpStatusCode.OK; + if (e.Error is WebException) + code = ((HttpWebResponse)((WebException)e.Error).Response).StatusCode; + + if (code == HttpStatusCode.BadGateway) { - // These are normal, retry the request automatically - Logger.DebugLog("502 error from capability " + _Client.Location); + // This is not good (server) protocol design, but it's normal. + // The CAPS server is a proxy that connects to a Squid + // cache which will time out periodically. The CAPS server + // interprets this as a generic error and returns a 502 to us + // that we ignore StartRequest(_PostData, _ContentType); } + else if (code != HttpStatusCode.OK) + { + // Status code was set to something unknown, this is a failure + Logger.DebugLog(String.Format("Caps error at {0}: {1}", _Client.Location, code)); + + try { OnComplete(this, null, e.Error); } + catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); } + } else { + // Status code was not set, some other error occurred. This is a failure Logger.DebugLog(String.Format("Caps error at {0}: {1}", _Client.Location, e.Error.Message)); try { OnComplete(this, null, e.Error); } @@ -178,14 +195,33 @@ namespace OpenMetaverse.Capabilities } else { - if (Helpers.StringContains(e.Error.Message, "502")) + // Some error occurred, try to figure out what happened + HttpStatusCode code = HttpStatusCode.OK; + if (e.Error is WebException) + code = ((HttpWebResponse)((WebException)e.Error).Response).StatusCode; + + if (code == HttpStatusCode.BadGateway) { - // These are normal, retry the request automatically - Logger.DebugLog("502 error from capability " + _Client.Location); + // This is not good (server) protocol design, but it's normal. + // The CAPS server is a proxy that connects to a Squid + // cache which will time out periodically. The CAPS server + // interprets this as a generic error and returns a 502 to us + // that we ignore StartRequest(_PostData, _ContentType); } + else if (code != HttpStatusCode.OK) + { + // Status code was set to something unknown, this is a failure + Logger.DebugLog(String.Format("Caps error at {0}: {1}", _Client.Location, code)); + + try { OnComplete(this, null, e.Error); } + catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); } + } else { + // Status code was not set, some other error occurred. This is a failure + Logger.DebugLog(String.Format("Caps error at {0}: {1}", _Client.Location, e.Error.Message)); + try { OnComplete(this, null, e.Error); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); } } diff --git a/OpenMetaverse/Capabilities/EventQueueClient.cs b/OpenMetaverse/Capabilities/EventQueueClient.cs index 36f39ea6..1c01fcaf 100644 --- a/OpenMetaverse/Capabilities/EventQueueClient.cs +++ b/OpenMetaverse/Capabilities/EventQueueClient.cs @@ -131,48 +131,33 @@ namespace OpenMetaverse.Capabilities if (e.Error != null) { - // Error occurred - string message = e.Error.Message.ToLower(); + HttpStatusCode code = HttpStatusCode.OK; + if (e.Error is WebException) + code = ((HttpWebResponse)((WebException)e.Error).Response).StatusCode; - // Check what kind of exception happened - if (Helpers.StringContains(message, "404") || Helpers.StringContains(message, "410")) + if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone) { - Logger.Log("Closing event queue at " + _Client.Location + " due to missing caps URI", + Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Client.Location), Helpers.LogLevel.Info); _Running = false; _Dead = true; } + else if (code == HttpStatusCode.BadGateway) + { + // This is not good (server) protocol design, but it's normal. + // The EventQueue server is a proxy that connects to a Squid + // cache which will time out periodically. The EventQueue server + // interprets this as a generic error and returns a 502 to us + // that we ignore + } else if (!e.Cancelled) { - HttpWebResponse errResponse = null; - - if (e.Error is WebException) + // Try to log a meaningful error message + if (code != HttpStatusCode.OK) { - WebException err = (WebException)e.Error; - errResponse = (HttpWebResponse)err.Response; - } - - // Figure out what type of error was thrown so we can print a meaningful - // error message - if (errResponse != null) - { - switch (errResponse.StatusCode) - { - case HttpStatusCode.BadGateway: - // This is not good (server) protocol design, but it's normal. - // The EventQueue server is a proxy that connects to a Squid - // cache which will time out periodically. The EventQueue server - // interprets this as a generic error and returns a 502 to us - // that we ignore - break; - default: - Logger.Log(String.Format( - "Unrecognized caps connection problem from {0}: {1} (Server returned: {2})", - _Client.Location, errResponse.StatusCode, errResponse.StatusDescription), - Helpers.LogLevel.Warning); - break; - } + Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}", + _Client.Location, code), Helpers.LogLevel.Warning); } else if (e.Error.InnerException != null) { diff --git a/OpenMetaverse/CapsToPacket.cs b/OpenMetaverse/CapsToPacket.cs index 788d004a..d7dd76be 100644 --- a/OpenMetaverse/CapsToPacket.cs +++ b/OpenMetaverse/CapsToPacket.cs @@ -86,7 +86,7 @@ namespace OpenMetaverse.Packets public static Packet FromXmlString(string xml) { System.Xml.XmlTextReader reader = - new System.Xml.XmlTextReader(new System.IO.MemoryStream(Helpers.StringToField(xml))); + new System.Xml.XmlTextReader(new System.IO.MemoryStream(Utils.StringToBytes(xml))); return FromLLSD(LLSDParser.DeserializeXml(reader)); } @@ -224,20 +224,17 @@ namespace OpenMetaverse.Packets } else if (fieldType == typeof(Vector3)) { - Vector3 vec = (Vector3)field.GetValue(block); - vec.FromLLSD(blockData[field.Name]); + Vector3 vec = ((LLSDArray)blockData[field.Name]).AsVector3(); field.SetValue(block, vec); } else if (fieldType == typeof(Vector4)) { - Vector4 vec = (Vector4)field.GetValue(block); - vec.FromLLSD(blockData[field.Name]); + Vector4 vec = ((LLSDArray)blockData[field.Name]).AsVector4(); field.SetValue(block, vec); } else if (fieldType == typeof(Quaternion)) { - Quaternion quat = (Quaternion)field.GetValue(block); - quat.FromLLSD(blockData[field.Name]); + Quaternion quat = ((LLSDArray)blockData[field.Name]).AsQuaternion(); field.SetValue(block, quat); } } @@ -257,7 +254,7 @@ namespace OpenMetaverse.Packets set.Invoke(block, new object[] { blockData[property.Name].AsBinary() }); } else - set.Invoke(block, new object[] { Helpers.StringToField(blockData[property.Name].AsString()) }); + set.Invoke(block, new object[] { Utils.StringToBytes(blockData[property.Name].AsString()) }); } } diff --git a/OpenMetaverse/DirectoryManager.cs b/OpenMetaverse/DirectoryManager.cs index a8a8fa7a..6598cc7f 100644 --- a/OpenMetaverse/DirectoryManager.cs +++ b/OpenMetaverse/DirectoryManager.cs @@ -371,7 +371,7 @@ namespace OpenMetaverse query.QueryData.Category = (uint)categories; query.QueryData.QueryFlags = (uint)(mature ? 0 : 2); query.QueryData.QueryID = queryID; - query.QueryData.QueryText = Helpers.StringToField(searchText); + query.QueryData.QueryText = Utils.StringToBytes(searchText); Client.Network.SendPacket(query); @@ -485,7 +485,7 @@ namespace OpenMetaverse find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.QueryData.QueryFlags = (uint)findFlags; - find.QueryData.QueryText = Helpers.StringToField(searchText); + find.QueryData.QueryText = Utils.StringToBytes(searchText); find.QueryData.QueryID = queryID; find.QueryData.QueryStart = queryStart; Client.Network.SendPacket(find); @@ -503,7 +503,7 @@ namespace OpenMetaverse find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.QueryData.QueryFlags = (uint)findFlags; - find.QueryData.QueryText = Helpers.StringToField(searchText); + find.QueryData.QueryText = Utils.StringToBytes(searchText); find.QueryData.QueryID = queryID; find.QueryData.QueryStart = queryStart; @@ -566,10 +566,10 @@ namespace OpenMetaverse find.TransactionData.TransactionID = transactionID; - find.QueryData.QueryText = Helpers.StringToField(searchText); + find.QueryData.QueryText = Utils.StringToBytes(searchText); find.QueryData.QueryFlags = (uint)findFlags; find.QueryData.Category = (sbyte)searchCategory; - find.QueryData.SimName = Helpers.StringToField(simulatorName); + find.QueryData.SimName = Utils.StringToBytes(simulatorName); Client.Network.SendPacket(find); return transactionID; @@ -616,7 +616,7 @@ namespace OpenMetaverse find.AgentData.SessionID = Client.Self.SessionID; find.QueryData.QueryID = queryID; - find.QueryData.QueryText = Helpers.StringToField(eventDay + "|" + (int)category + "|" + searchText); + find.QueryData.QueryText = Utils.StringToBytes(eventDay + "|" + (int)category + "|" + searchText); find.QueryData.QueryFlags = showMature ? (uint)32 : (uint)8224; find.QueryData.QueryStart = (int)queryStart; @@ -680,11 +680,11 @@ namespace OpenMetaverse { Classified classified = new Classified(); - classified.CreationDate = Helpers.UnixTimeToDateTime(block.CreationDate); - classified.ExpirationDate = Helpers.UnixTimeToDateTime(block.ExpirationDate); + classified.CreationDate = Utils.UnixTimeToDateTime(block.CreationDate); + classified.ExpirationDate = Utils.UnixTimeToDateTime(block.ExpirationDate); classified.Flags = block.ClassifiedFlags; classified.ID = block.ClassifiedID; - classified.Name = Helpers.FieldToUTF8String(block.Name); + classified.Name = Utils.BytesToString(block.Name); classified.Price = block.PriceForListing; classifieds.Add(classified); @@ -708,7 +708,7 @@ namespace OpenMetaverse dirParcel.ActualArea = block.ActualArea; dirParcel.ID = block.ParcelID; - dirParcel.Name = Helpers.FieldToUTF8String(block.Name); + dirParcel.Name = Utils.BytesToString(block.Name); dirParcel.SalePrice = block.SalePrice; dirParcel.Auction = block.Auction; dirParcel.ForSale = block.ForSale; @@ -730,8 +730,8 @@ namespace OpenMetaverse foreach (DirPeopleReplyPacket.QueryRepliesBlock reply in peopleReply.QueryReplies) { AgentSearchData searchData = new AgentSearchData(); searchData.Online = reply.Online; - searchData.FirstName = Helpers.FieldToUTF8String(reply.FirstName); - searchData.LastName = Helpers.FieldToUTF8String(reply.LastName); + searchData.FirstName = Utils.BytesToString(reply.FirstName); + searchData.LastName = Utils.BytesToString(reply.LastName); searchData.AgentID = reply.AgentID; matches.Add(searchData); } @@ -750,7 +750,7 @@ namespace OpenMetaverse { GroupSearchData groupsData = new GroupSearchData(); groupsData.GroupID = reply.GroupID; - groupsData.GroupName = Helpers.FieldToUTF8String(reply.GroupName); + groupsData.GroupName = Utils.BytesToString(reply.GroupName); groupsData.Members = reply.Members; matches.Add(groupsData); } @@ -770,15 +770,15 @@ namespace OpenMetaverse { PlacesSearchData place = new PlacesSearchData(); place.OwnerID = block.OwnerID; - place.Name = Helpers.FieldToUTF8String(block.Name); - place.Desc = Helpers.FieldToUTF8String(block.Desc); + place.Name = Utils.BytesToString(block.Name); + place.Desc = Utils.BytesToString(block.Desc); place.ActualArea = block.ActualArea; place.BillableArea = block.BillableArea; place.Flags = block.Flags; place.GlobalX = block.GlobalX; place.GlobalY = block.GlobalY; place.GlobalZ = block.GlobalZ; - place.SimName = Helpers.FieldToUTF8String(block.SimName); + place.SimName = Utils.BytesToString(block.SimName); place.SnapshotID = block.SnapshotID; place.Dwell = block.Dwell; place.Price = block.Price; @@ -801,9 +801,9 @@ namespace OpenMetaverse { EventsSearchData eventsData = new EventsSearchData(); eventsData.Owner = reply.OwnerID; - eventsData.Name = Helpers.FieldToUTF8String(reply.Name); + eventsData.Name = Utils.BytesToString(reply.Name); eventsData.ID = reply.EventID; - eventsData.Date = Helpers.FieldToUTF8String(reply.Date); + eventsData.Date = Utils.BytesToString(reply.Date); eventsData.Time = reply.UnixTime; eventsData.Flags = (EventFlags)reply.EventFlags; matches.Add(eventsData); @@ -821,17 +821,17 @@ namespace OpenMetaverse EventInfoReplyPacket eventReply = (EventInfoReplyPacket)packet; EventInfo evinfo = new EventInfo(); evinfo.ID = eventReply.EventData.EventID; - evinfo.Name = Helpers.FieldToUTF8String(eventReply.EventData.Name); - evinfo.Desc = Helpers.FieldToUTF8String(eventReply.EventData.Desc); + evinfo.Name = Utils.BytesToString(eventReply.EventData.Name); + evinfo.Desc = Utils.BytesToString(eventReply.EventData.Desc); evinfo.Amount = eventReply.EventData.Amount; evinfo.Category = (EventCategories)Helpers.BytesToUInt(eventReply.EventData.Category); evinfo.Cover = eventReply.EventData.Cover; - evinfo.Creator = (UUID)Helpers.FieldToUTF8String(eventReply.EventData.Creator); - evinfo.Date = Helpers.FieldToUTF8String(eventReply.EventData.Date); + evinfo.Creator = (UUID)Utils.BytesToString(eventReply.EventData.Creator); + evinfo.Date = Utils.BytesToString(eventReply.EventData.Date); evinfo.DateUTC = eventReply.EventData.DateUTC; evinfo.Duration = eventReply.EventData.Duration; evinfo.Flags = (EventFlags)eventReply.EventData.EventFlags; - evinfo.SimName = Helpers.FieldToUTF8String(eventReply.EventData.SimName); + evinfo.SimName = Utils.BytesToString(eventReply.EventData.SimName); evinfo.GlobalPos = eventReply.EventData.GlobalPos; try { OnEventInfo(evinfo); } diff --git a/OpenMetaverse/EstateTools.cs b/OpenMetaverse/EstateTools.cs index ec2437a8..6c9a9eac 100644 --- a/OpenMetaverse/EstateTools.cs +++ b/OpenMetaverse/EstateTools.cs @@ -172,7 +172,7 @@ namespace OpenMetaverse LandStatRequestPacket p = new LandStatRequestPacket(); p.AgentData.AgentID = Client.Self.AgentID; p.AgentData.SessionID = Client.Self.SessionID; - p.RequestData.Filter = Helpers.StringToField(filter); + p.RequestData.Filter = Utils.StringToBytes(filter); p.RequestData.ParcelLocalID = parcelLocalID; p.RequestData.ReportType = (uint)reportType; p.RequestData.RequestFlags = requestFlags; @@ -209,7 +209,7 @@ namespace OpenMetaverse OnGetCovenant( reply.Data.CovenantID, reply.Data.CovenantTimestamp, - Helpers.FieldToUTF8String(reply.Data.EstateName), + Utils.BytesToString(reply.Data.EstateName), reply.Data.EstateOwnerID); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } @@ -223,18 +223,18 @@ namespace OpenMetaverse { EstateOwnerMessagePacket message = (EstateOwnerMessagePacket)packet; uint estateID; - string method = Helpers.FieldToUTF8String(message.MethodData.Method); + string method = Utils.BytesToString(message.MethodData.Method); List parameters = new List(); if (method == "estateupdateinfo") { - string estateName = Helpers.FieldToUTF8String(message.ParamList[0].Parameter); - UUID estateOwner = new UUID(Helpers.FieldToUTF8String(message.ParamList[1].Parameter)); + string estateName = Utils.BytesToString(message.ParamList[0].Parameter); + UUID estateOwner = new UUID(Utils.BytesToString(message.ParamList[1].Parameter)); estateID = Helpers.BytesToUInt(message.ParamList[2].Parameter); /* foreach (EstateOwnerMessagePacket.ParamListBlock param in message.ParamList) { - parameters.Add(Helpers.FieldToUTF8String(param.Parameter)); + parameters.Add(Utils.BytesToString(param.Parameter)); } */ bool denyNoPaymentInfo; @@ -270,7 +270,7 @@ namespace OpenMetaverse for (int i = 5; i < message.ParamList.Length; i++) { UUID managerID; - if (UUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out managerID)) + if (UUID.TryParse(Utils.BytesToString(message.ParamList[i].Parameter), out managerID)) { managers.Add(managerID); } @@ -291,7 +291,7 @@ namespace OpenMetaverse for (int i = 5; i < message.ParamList.Length; i++) { UUID bannedID; - if (UUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out bannedID)) + if (UUID.TryParse(Utils.BytesToString(message.ParamList[i].Parameter), out bannedID)) { bannedUsers.Add(bannedID); } @@ -312,7 +312,7 @@ namespace OpenMetaverse for (int i = 5; i < message.ParamList.Length; i++) { UUID userID; - if (UUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out userID)) + if (UUID.TryParse(Utils.BytesToString(message.ParamList[i].Parameter), out userID)) { allowedUsers.Add(userID); } @@ -333,7 +333,7 @@ namespace OpenMetaverse for (int i = 5; i < message.ParamList.Length; i++) { UUID groupID; - if (UUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out groupID)) + if (UUID.TryParse(Utils.BytesToString(message.ParamList[i].Parameter), out groupID)) { allowedGroups.Add(groupID); } @@ -355,7 +355,7 @@ namespace OpenMetaverse for (int i = 5; i < message.ParamList.Length; i++) { UUID managerID; - if (UUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out managerID)) + if (UUID.TryParse(Utils.BytesToString(message.ParamList[i].Parameter), out managerID)) { managers.Add(managerID); } @@ -372,7 +372,7 @@ namespace OpenMetaverse Console.WriteLine("--- " + method + " ---"); foreach (EstateOwnerMessagePacket.ParamListBlock block in message.ParamList) { - Console.WriteLine(Helpers.FieldToUTF8String(block.Parameter)); + Console.WriteLine(Utils.BytesToString(block.Parameter)); } Console.WriteLine("------"); */ @@ -396,8 +396,8 @@ namespace OpenMetaverse task.Score = rep.Score; task.TaskID = rep.TaskID; task.TaskLocalID = rep.TaskLocalID; - task.TaskName = Helpers.FieldToUTF8String(rep.TaskName); - task.OwnerName = Helpers.FieldToUTF8String(rep.OwnerName); + task.TaskName = Utils.BytesToString(rep.TaskName); + task.OwnerName = Utils.BytesToString(rep.OwnerName); Tasks.Add(task); } @@ -449,12 +449,12 @@ namespace OpenMetaverse estate.AgentData.SessionID = Client.Self.SessionID; estate.AgentData.TransactionID = UUID.Zero; estate.MethodData.Invoice = UUID.Random(); - estate.MethodData.Method = Helpers.StringToField(method); + estate.MethodData.Method = Utils.StringToBytes(method); estate.ParamList = new EstateOwnerMessagePacket.ParamListBlock[listParams.Count]; for (int i = 0; i < listParams.Count; i++) { estate.ParamList[i] = new EstateOwnerMessagePacket.ParamListBlock(); - estate.ParamList[i].Parameter = Helpers.StringToField(listParams[i]); + estate.ParamList[i].Parameter = Utils.StringToBytes(listParams[i]); } Client.Network.SendPacket((Packet)estate); } diff --git a/OpenMetaverse/GridManager.cs b/OpenMetaverse/GridManager.cs index bab4649f..22aaf5d5 100644 --- a/OpenMetaverse/GridManager.cs +++ b/OpenMetaverse/GridManager.cs @@ -281,7 +281,7 @@ namespace OpenMetaverse request.AgentData.Flags = (uint)layer; request.AgentData.EstateID = 0; // Filled in on the sim request.AgentData.Godlike = false; // Filled in on the sim - request.NameData.Name = Helpers.StringToField(regionName.ToLower()); + request.NameData.Name = Utils.StringToBytes(regionName.ToLower()); Client.Network.SendPacket(request); } @@ -495,7 +495,7 @@ namespace OpenMetaverse region.X = block.X; region.Y = block.Y; - region.Name = Helpers.FieldToUTF8String(block.Name); + region.Name = Utils.BytesToString(block.Name); // RegionFlags seems to always be zero here? region.RegionFlags = (Simulator.RegionFlags)block.RegionFlags; region.WaterHeight = block.WaterHeight; @@ -529,7 +529,7 @@ namespace OpenMetaverse for (int i = 0; i < reply.Data.Length; i++) { - string name = Helpers.FieldToUTF8String(reply.Data[i].Name); + string name = Utils.BytesToString(reply.Data[i].Name); switch (type) { diff --git a/OpenMetaverse/GroupManager.cs b/OpenMetaverse/GroupManager.cs index defb1549..e2f9e72b 100644 --- a/OpenMetaverse/GroupManager.cs +++ b/OpenMetaverse/GroupManager.cs @@ -235,7 +235,7 @@ namespace OpenMetaverse //I guess this is how this works, no gaurentees string lsd = "" + AttachmentID.ToString() + "" + OwnerID.ToString() + ""; - return Helpers.StringToField(lsd); + return Utils.StringToBytes(lsd); } } @@ -812,11 +812,11 @@ namespace OpenMetaverse //Fill in group data cgrp.GroupData = new CreateGroupRequestPacket.GroupDataBlock(); cgrp.GroupData.AllowPublish = group.AllowPublish; - cgrp.GroupData.Charter = Helpers.StringToField(group.Charter); + cgrp.GroupData.Charter = Utils.StringToBytes(group.Charter); cgrp.GroupData.InsigniaID = group.InsigniaID; cgrp.GroupData.MaturePublish = group.MaturePublish; cgrp.GroupData.MembershipFee = group.MembershipFee; - cgrp.GroupData.Name = Helpers.StringToField(group.Name); + cgrp.GroupData.Name = Utils.StringToBytes(group.Name); cgrp.GroupData.OpenEnrollment = group.OpenEnrollment; cgrp.GroupData.ShowInList = group.ShowInList; //Send it @@ -837,7 +837,7 @@ namespace OpenMetaverse cgrp.GroupData = new UpdateGroupInfoPacket.GroupDataBlock(); cgrp.GroupData.GroupID = id; cgrp.GroupData.AllowPublish = group.AllowPublish; - cgrp.GroupData.Charter = Helpers.StringToField(group.Charter); + cgrp.GroupData.Charter = Utils.StringToBytes(group.Charter); cgrp.GroupData.InsigniaID = group.InsigniaID; cgrp.GroupData.MaturePublish = group.MaturePublish; cgrp.GroupData.MembershipFee = group.MembershipFee; @@ -877,10 +877,10 @@ namespace OpenMetaverse gru.AgentData.SessionID = Client.Self.SessionID; gru.AgentData.GroupID = group; gru.RoleData = new GroupRoleUpdatePacket.RoleDataBlock[1]; - gru.RoleData[0].Name = Helpers.StringToField(role.Name); - gru.RoleData[0].Description = Helpers.StringToField(role.Description); + gru.RoleData[0].Name = Utils.StringToBytes(role.Name); + gru.RoleData[0].Description = Utils.StringToBytes(role.Description); gru.RoleData[0].Powers = (ulong)role.Powers; - gru.RoleData[0].Title = Helpers.StringToField(role.Title); + gru.RoleData[0].Title = Utils.StringToBytes(role.Title); gru.RoleData[0].UpdateType = (byte)GroupRoleUpdate.UpdateAll; Client.Network.SendPacket(gru); } @@ -895,10 +895,10 @@ namespace OpenMetaverse gru.AgentData.SessionID = Client.Self.SessionID; gru.AgentData.GroupID = group; gru.RoleData = new GroupRoleUpdatePacket.RoleDataBlock[1]; - gru.RoleData[0].Name = Helpers.StringToField(role.Name); - gru.RoleData[0].Description = Helpers.StringToField(role.Description); + gru.RoleData[0].Name = Utils.StringToBytes(role.Name); + gru.RoleData[0].Description = Utils.StringToBytes(role.Description); gru.RoleData[0].Powers = (ulong)role.Powers; - gru.RoleData[0].Title = Helpers.StringToField(role.Title); + gru.RoleData[0].Title = Utils.StringToBytes(role.Title); gru.RoleData[0].UpdateType = (byte)GroupRoleUpdate.Create; Client.Network.SendPacket(gru); } @@ -962,7 +962,7 @@ namespace OpenMetaverse p.AgentData.AgentID = Client.Self.AgentID; p.AgentData.SessionID = Client.Self.SessionID; p.ProposalData.GroupID = group; - p.ProposalData.ProposalText = Helpers.StringToField(prop.VoteText); + p.ProposalData.ProposalText = Utils.StringToBytes(prop.VoteText); p.ProposalData.Quorum = prop.Quorum; p.ProposalData.Majority = prop.Majority; p.ProposalData.Duration = prop.Duration; @@ -997,7 +997,7 @@ namespace OpenMetaverse group.ID = block.GroupID; group.InsigniaID = block.GroupInsigniaID; - group.Name = Helpers.FieldToUTF8String(block.GroupName); + group.Name = Utils.BytesToString(block.GroupName); group.Powers = (GroupPowers)block.GroupPowers; group.Contribution = block.Contribution; group.AcceptNotices = block.AcceptNotices; @@ -1005,7 +1005,7 @@ namespace OpenMetaverse currentGroups[block.GroupID] = group; if (!GroupName2KeyCache.ContainsKey(block.GroupID)) - GroupName2KeyCache.SafeAdd(block.GroupID, Helpers.FieldToUTF8String(block.GroupName)); + GroupName2KeyCache.SafeAdd(block.GroupID, Utils.BytesToString(block.GroupName)); } try { OnCurrentGroups(currentGroups); } @@ -1031,16 +1031,16 @@ namespace OpenMetaverse group.ID = profile.GroupData.GroupID; group.AllowPublish = profile.GroupData.AllowPublish; - group.Charter = Helpers.FieldToUTF8String(profile.GroupData.Charter); + group.Charter = Utils.BytesToString(profile.GroupData.Charter); group.FounderID = profile.GroupData.FounderID; group.GroupMembershipCount = profile.GroupData.GroupMembershipCount; group.GroupRolesCount = profile.GroupData.GroupRolesCount; group.InsigniaID = profile.GroupData.InsigniaID; group.MaturePublish = profile.GroupData.MaturePublish; group.MembershipFee = profile.GroupData.MembershipFee; - group.MemberTitle = Helpers.FieldToUTF8String(profile.GroupData.MemberTitle); + group.MemberTitle = Utils.BytesToString(profile.GroupData.MemberTitle); group.Money = profile.GroupData.Money; - group.Name = Helpers.FieldToUTF8String(profile.GroupData.Name); + group.Name = Utils.BytesToString(profile.GroupData.Name); group.OpenEnrollment = profile.GroupData.OpenEnrollment; group.OwnerRole = profile.GroupData.OwnerRole; group.Powers = (GroupPowers)profile.GroupData.PowersMask; @@ -1062,7 +1062,7 @@ namespace OpenMetaverse { GroupTitle groupTitle = new GroupTitle(); - groupTitle.Title = Helpers.FieldToUTF8String(block.Title); + groupTitle.Title = Utils.BytesToString(block.Title); groupTitle.Selected = block.Selected; groupTitleCache[block.RoleID] = groupTitle; @@ -1092,9 +1092,9 @@ namespace OpenMetaverse groupMember.ID = block.AgentID; groupMember.Contribution = block.Contribution; groupMember.IsOwner = block.IsOwner; - groupMember.OnlineStatus = Helpers.FieldToUTF8String(block.OnlineStatus); + groupMember.OnlineStatus = Utils.BytesToString(block.OnlineStatus); groupMember.Powers = (GroupPowers)block.AgentPowers; - groupMember.Title = Helpers.FieldToUTF8String(block.Title); + groupMember.Title = Utils.BytesToString(block.Title); groupMemberCache[block.AgentID] = groupMember; } @@ -1126,10 +1126,10 @@ namespace OpenMetaverse GroupRole groupRole = new GroupRole(); groupRole.ID = block.RoleID; - groupRole.Description = Helpers.FieldToUTF8String(block.Description); - groupRole.Name = Helpers.FieldToUTF8String(block.Name); + groupRole.Description = Utils.BytesToString(block.Description); + groupRole.Name = Utils.BytesToString(block.Name); groupRole.Powers = (GroupPowers)block.Powers; - groupRole.Title = Helpers.FieldToUTF8String(block.Title); + groupRole.Title = Utils.BytesToString(block.Title); groupRoleCache[block.RoleID] = groupRole; } @@ -1211,7 +1211,7 @@ namespace OpenMetaverse account.IntervalDays = summary.MoneyData.IntervalDays; account.LandTaxCurrent = summary.MoneyData.LandTaxCurrent; account.LandTaxEstimate = summary.MoneyData.LandTaxEstimate; - account.LastTaxDate = Helpers.FieldToUTF8String(summary.MoneyData.LastTaxDate); + account.LastTaxDate = Utils.BytesToString(summary.MoneyData.LastTaxDate); account.LightTaxCurrent = summary.MoneyData.LightTaxCurrent; account.LightTaxEstimate = summary.MoneyData.LightTaxEstimate; account.NonExemptMembers = summary.MoneyData.NonExemptMembers; @@ -1219,8 +1219,8 @@ namespace OpenMetaverse account.ObjectTaxEstimate = summary.MoneyData.ObjectTaxEstimate; account.ParcelDirFeeCurrent = summary.MoneyData.ParcelDirFeeCurrent; account.ParcelDirFeeEstimate = summary.MoneyData.ParcelDirFeeEstimate; - account.StartDate = Helpers.FieldToUTF8String(summary.MoneyData.StartDate); - account.TaxDate = Helpers.FieldToUTF8String(summary.MoneyData.TaxDate); + account.StartDate = Utils.BytesToString(summary.MoneyData.StartDate); + account.TaxDate = Utils.BytesToString(summary.MoneyData.TaxDate); account.TotalCredits = summary.MoneyData.TotalCredits; account.TotalDebits = summary.MoneyData.TotalDebits; @@ -1235,7 +1235,7 @@ namespace OpenMetaverse { CreateGroupReplyPacket reply = (CreateGroupReplyPacket)packet; - string message = Helpers.FieldToUTF8String(reply.ReplyData.Message); + string message = Utils.BytesToString(reply.ReplyData.Message); try { OnGroupCreated(reply.ReplyData.GroupID, reply.ReplyData.Success, message); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } @@ -1273,9 +1273,9 @@ namespace OpenMetaverse foreach (UUIDGroupNameReplyPacket.UUIDNameBlockBlock block in blocks) { - groupNames.Add(block.ID, Helpers.FieldToUTF8String(block.GroupName)); + groupNames.Add(block.ID, Utils.BytesToString(block.GroupName)); if (!GroupName2KeyCache.ContainsKey(block.ID)) - GroupName2KeyCache.SafeAdd(block.ID, Helpers.FieldToUTF8String(block.GroupName)); + GroupName2KeyCache.SafeAdd(block.ID, Utils.BytesToString(block.GroupName)); } if (OnGroupNames != null) diff --git a/OpenMetaverse/Helpers.cs b/OpenMetaverse/Helpers.cs index ef35a073..dabbff13 100644 --- a/OpenMetaverse/Helpers.cs +++ b/OpenMetaverse/Helpers.cs @@ -36,34 +36,6 @@ namespace OpenMetaverse /// public static class Helpers { - /// - /// Operating system - /// - public enum Platform - { - /// Unknown - Unknown, - /// Microsoft Windows - Windows, - /// Microsoft Windows CE - WindowsCE, - /// Linux - Linux, - /// Apple OSX - OSX - } - - /// - /// Runtime platform - /// - public enum Runtime - { - /// .NET runtime - Windows, - /// Mono runtime: http://www.mono-project.com/ - Mono - } - /// This header flag signals that ACKs are appended to the packet public const byte MSG_APPENDED_ACKS = 0x10; /// This header flag signals that this packet has been sent before @@ -72,23 +44,8 @@ namespace OpenMetaverse public const byte MSG_RELIABLE = 0x40; /// This header flag signals that the message is compressed using zerocoding public const byte MSG_ZEROCODED = 0x80; - /// Used for converting degrees to radians - public const double DEG_TO_RAD = Math.PI / 180.0d; - /// Used for converting radians to degrees - public const double RAD_TO_DEG = 180.0d / Math.PI; - /// - public const float PI = (float)Math.PI; - /// - public const float TWO_PI = (float)(Math.PI * 2d); -#if PocketPC - public static string NewLine = "\r\n"; -#else - public static string NewLine = Environment.NewLine; -#endif - - /// UNIX epoch in DateTime format - public static DateTime Epoch = new DateTime(1970, 1, 1); + public static readonly string NewLine = Environment.NewLine; /// /// Passed to Logger.Log() to identify the severity of a log entry @@ -115,11 +72,6 @@ namespace OpenMetaverse Debug }; - /// Provide a single instance of the MD5 class to avoid making - /// duplicate copies - public static System.Security.Cryptography.MD5 MD5Builder = - new System.Security.Cryptography.MD5CryptoServiceProvider(); - /// Provide a single instance of the CultureInfo class to /// help parsing in situations where the grid assumes an en-us /// culture @@ -133,7 +85,7 @@ namespace OpenMetaverse /// public static short TEOffsetShort(float offset) { - offset = MathHelper.Clamp(offset, -1.0f, 1.0f); + offset = Utils.Clamp(offset, -1.0f, 1.0f); offset *= 32767.0f; return (short)Math.Round(offset); } @@ -346,11 +298,14 @@ namespace OpenMetaverse } /// - /// + /// Convert four bytes in little endian ordering to a floating point + /// value /// - /// - /// - /// + /// Byte array containing a little ending floating + /// point value + /// Starting position of the floating point value in + /// the byte array + /// Single precision value public static float BytesToFloat(byte[] bytes, int pos) { if (!BitConverter.IsLittleEndian) Array.Reverse(bytes, pos, 4); @@ -408,7 +363,7 @@ namespace OpenMetaverse /// A single byte representing the original float value public static byte FloatToByte(float val, float lower, float upper) { - val = MathHelper.Clamp(val, lower, upper); + val = Utils.Clamp(val, lower, upper); // Normalize the value val -= lower; val /= (upper - lower); @@ -492,30 +447,6 @@ namespace OpenMetaverse return fval; } - /// - /// Convert an IP address object to an unsigned 32-bit integer - /// - /// IP address to convert - /// 32-bit unsigned integer holding the IP address bits - public static uint IPToUInt(System.Net.IPAddress address) - { - byte[] bytes = address.GetAddressBytes(); - return (uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]); - } - - /// - /// Convert a variable length UTF8 byte array to a string - /// - /// The UTF8 encoded byte array to convert - /// The decoded string - public static string FieldToUTF8String(byte[] bytes) - { - if (bytes.Length > 0 && bytes[bytes.Length - 1] == 0x00) - return UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1); - else - return UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length); - } - /// /// Convert a variable length field (byte array) to a string /// @@ -591,202 +522,6 @@ namespace OpenMetaverse } } - /// - /// Converts a byte array to a string containing hexadecimal characters - /// - /// The byte array to convert to a string - /// The name of the field to prepend to each - /// line of the string - /// A string containing hexadecimal characters on multiple - /// lines. Each line is prepended with the field name - public static string FieldToHexString(byte[] bytes, string fieldName) - { - return FieldToHexString(bytes, bytes.Length, fieldName); - } - - /// - /// Converts a byte array to a string containing hexadecimal characters - /// - /// The byte array to convert to a string - /// Number of bytes in the array to parse - /// The name of the field to prepend to each - /// line of the string - /// A string containing hexadecimal characters on multiple - /// lines. Each line is prepended with the field name - public static string FieldToHexString(byte[] bytes, int length, string fieldName) - { - StringBuilder output = new StringBuilder(); - - for (int i = 0; i < length; i += 16) - { - if (i != 0) - output.Append('\n'); - - if (!String.IsNullOrEmpty(fieldName)) - { - output.Append(fieldName); - output.Append(": "); - } - - for (int j = 0; j < 16; j++) - { - if ((i + j) < length) - output.Append(String.Format("{0:X2} ", bytes[i + j])); - else - output.Append(" "); - } - } - - return output.ToString(); - } - - ///// - ///// Converts a string containing hexadecimal characters to a byte array - ///// - ///// String containing hexadecimal characters - ///// The converted byte array - //public static byte[] HexStringToField(string hexString) - //{ - // string newString = ""; - // char c; - - // // FIXME: For each line of the string, if a colon is found - // // remove everything before it - - // // remove all non A-F, 0-9, characters - // for (int i = 0; i < hexString.Length; i++) - // { - // c = hexString[i]; - // if (IsHexDigit(c)) - // newString += c; - // } - - // // if odd number of characters, discard last character - // if (newString.Length % 2 != 0) - // { - // newString = newString.Substring(0, newString.Length - 1); - // } - - // int byteLength = newString.Length / 2; - // byte[] bytes = new byte[byteLength]; - // string hex; - // int j = 0; - // for (int i = 0; i < bytes.Length; i++) - // { - // hex = new String(new Char[] { newString[j], newString[j + 1] }); - // bytes[i] = HexToByte(hex); - // j = j + 2; - // } - // return bytes; - //} - - /// - /// Returns the string between and exclusive of two search characters - /// - /// Source string - /// Beginning and exclusive of the substring - /// End and exclusive of the substring - /// Substring between the start and end characters - public static string StringBetween(string src, char start, char end) - { - string ret = String.Empty; - int idxStart = src.IndexOf(start); - if (idxStart != -1) - { - ++idxStart; - int idxEnd = src.IndexOf(end, idxStart); - if (idxEnd != -1) - { - ret = src.Substring(idxStart, idxEnd - idxStart); - } - } - return ret; - } - - /// - /// Convert a string to a UTF8 encoded byte array - /// - /// The string to convert - /// A null-terminated UTF8 byte array - public static byte[] StringToField(string str) - { - if (str.Length == 0) { return new byte[0]; } - if (!str.EndsWith("\0")) { str += "\0"; } - return System.Text.UTF8Encoding.UTF8.GetBytes(str); - } - - /// - /// Gets a unix timestamp for the current time - /// - /// An unsigned integer representing a unix timestamp for now - public static uint GetUnixTime() - { - return (uint)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; - } - - /// - /// Convert a UNIX timestamp to a native DateTime object - /// - /// An unsigned integer representing a UNIX - /// timestamp - /// A DateTime object containing the same time specified in - /// the given timestamp - public static DateTime UnixTimeToDateTime(uint timestamp) - { - System.DateTime dateTime = Epoch; - - // Add the number of seconds in our UNIX timestamp - dateTime = dateTime.AddSeconds(timestamp); - - return dateTime; - } - - /// - /// Convert a UNIX timestamp to a native DateTime object - /// - /// A signed integer representing a UNIX - /// timestamp - /// A DateTime object containing the same time specified in - /// the given timestamp - public static DateTime UnixTimeToDateTime(int timestamp) - { -#if PocketPC - System.DateTime dateTime = Epoch; - - // Add the number of seconds in our UNIX timestamp - dateTime = dateTime.AddSeconds(timestamp); - - return dateTime; -#else - return DateTime.FromBinary(timestamp); -#endif - } - - /// - /// Convert a native DateTime object to a UNIX timestamp - /// - /// A DateTime object you want to convert to a - /// timestamp - /// An unsigned integer representing a UNIX timestamp - public static uint DateTimeToUnixTime(DateTime time) - { - TimeSpan ts = (time - new DateTime(1970, 1, 1, 0, 0, 0)); - return (uint)ts.TotalSeconds; - } - - /// - /// Swap two values - /// - /// Type of the values to swap - /// First value - /// Second value - public static void Swap(ref T lhs, ref T rhs) - { - T temp = lhs; - lhs = rhs; - rhs = temp; - } - /// /// Decode a zerocoded byte array, used to decompress packets marked /// with the zerocoded flag @@ -842,38 +577,12 @@ namespace OpenMetaverse catch (Exception) { Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}", - i, srclen, bodylen, zerolen, FieldToHexString(src, srclen, null)), LogLevel.Error); + i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null)), LogLevel.Error); } return 0; } - /// - /// Decode enough of a byte array to get the packet ID. Data before and - /// after the packet ID is undefined. - /// - /// The byte array to decode - /// The output byte array to encode to - public static void ZeroDecodeCommand(byte[] src, byte[] dest) - { - for (int srcPos = 6, destPos = 6; destPos < 10; ++srcPos) - { - if (src[srcPos] == 0x00) - { - for (byte j = 0; j < src[srcPos + 1]; ++j) - { - dest[destPos++] = 0x00; - } - - ++srcPos; - } - else - { - dest[destPos++] = src[srcPos]; - } - } - } - /// /// Encode a byte array with zerocoding. Used to compress packets marked /// with the zerocoded flag. Any zeroes in the array are compressed down @@ -1000,26 +709,6 @@ namespace OpenMetaverse return CRC; } - /// - /// Calculate the MD5 hash of a given string - /// - /// The password to hash - /// An MD5 hash in string format, with $1$ prepended - public static string MD5(string password) - { - StringBuilder digest = new StringBuilder(); - byte[] hash; - lock(MD5Builder) hash = MD5Builder.ComputeHash(ASCIIEncoding.Default.GetBytes(password)); - - // Convert the hash to a hex string - foreach (byte b in hash) - { - digest.AppendFormat(Helpers.EnUsCulture, "{0:x2}", b); - } - - return "$1$" + digest.ToString(); - } - /// /// Attempts to load a file embedded in the assembly /// @@ -1067,49 +756,6 @@ namespace OpenMetaverse return null; } - /// - /// Get the current running platform - /// - /// Enumeration of the current platform we are running on - public static Platform GetRunningPlatform() - { - const string OSX_CHECK_FILE = "/Library/Extensions.kextcache"; - - if (Environment.OSVersion.Platform == PlatformID.WinCE) - { - return Platform.WindowsCE; - } - else - { - int plat = (int)Environment.OSVersion.Platform; - - if ((plat != 4) && (plat != 128)) - { - return Platform.Windows; - } - else - { - if (System.IO.File.Exists(OSX_CHECK_FILE)) - return Platform.OSX; - else - return Platform.Linux; - } - } - } - - /// - /// Get the current running runtime - /// - /// Enumeration of the current runtime we are running on - public static Runtime GetRunningRuntime() - { - Type t = Type.GetType("Mono.Runtime"); - if (t != null) - return Runtime.Mono; - else - return Runtime.Windows; - } - /// /// Converts a list of primitives to an object that can be serialized /// with the LLSD system @@ -1156,126 +802,5 @@ namespace OpenMetaverse uint fixedState = (((byte)state & ATTACHMENT_MASK) >> 4) | (((byte)state & ~ATTACHMENT_MASK) << 4); return (AttachmentPoint)fixedState; } - - #region Platform Helper Functions - - public static bool TryParse(string s, out DateTime result) - { -#if PocketPC - try { result = DateTime.Parse(s); return true; } - catch (FormatException) { result = Helpers.Epoch; return false; } -#else - return DateTime.TryParse(s, out result); -#endif - } - - public static bool TryParse(string s, out int result) - { -#if PocketPC - try { result = Int32.Parse(s); return true; } - catch (FormatException) { result = 0; return false; } -#else - return Int32.TryParse(s, out result); -#endif - } - - public static bool TryParse(string s, out uint result) - { -#if PocketPC - try { result = UInt32.Parse(s); return true; } - catch (FormatException) { result = 0; return false; } -#else - return UInt32.TryParse(s, out result); -#endif - } - - public static bool TryParse(string s, out ulong result) - { -#if PocketPC - try { result = UInt64.Parse(s); return true; } - catch (FormatException) { result = 0; return false; } -#else - return UInt64.TryParse(s, out result); -#endif - } - - public static bool TryParse(string s, out float result) - { -#if PocketPC - try { result = Single.Parse(s, System.Globalization.NumberStyles.Float, Helpers.EnUsCulture.NumberFormat); return true; } - catch (FormatException) { result = 0f; return false; } -#else - return Single.TryParse(s, System.Globalization.NumberStyles.Float, Helpers.EnUsCulture.NumberFormat, out result); -#endif - } - - public static bool TryParse(string s, out double result) - { -#if PocketPC - try { result = Double.Parse(s, System.Globalization.NumberStyles.Float, Helpers.EnUsCulture.NumberFormat); return true; } - catch (FormatException) { result = 0d; return false; } -#else - return Double.TryParse(s, System.Globalization.NumberStyles.Float, Helpers.EnUsCulture.NumberFormat, out result); -#endif - } - - public static bool TryParse(string s, out System.Net.IPAddress result) - { -#if PocketPC - try { result = System.Net.IPAddress.Parse(s); return true; } - catch (FormatException) { result = System.Net.IPAddress.Loopback; return false; } -#else - return System.Net.IPAddress.TryParse(s, out result); -#endif - } - - public static bool TryParse(string s, out UUID result) - { - return UUID.TryParse(s, out result); - } - - public static bool TryParse(string s, out Vector3 result) - { - return Vector3.TryParse(s, out result); - } - - public static bool TryParseHex(string s, out uint result) - { -#if PocketPC - try { result = UInt32.Parse(s, System.Globalization.NumberStyles.HexNumber, Helpers.EnUsCulture.NumberFormat); return true; } - catch (FormatException) { result = 0; return false; } -#else - return UInt32.TryParse(s, System.Globalization.NumberStyles.HexNumber, Helpers.EnUsCulture.NumberFormat, out result); -#endif - } - - public static bool StringContains(string haystack, string needle) - { -#if PocketPC - return (haystack.IndexOf(needle) != -1); -#else - return haystack.Contains(needle); -#endif - } - - public static bool StringSplitAt(string input, string separator, out string before, out string after) - { - int index = input.IndexOf(separator); - - if (index != -1) - { - before = input.Substring(0, index); - after = input.Substring(index); - return true; - } - else - { - before = String.Empty; - after = String.Empty; - return false; - } - } - - #endregion Platform Helper Functions } } diff --git a/OpenMetaverse/InventoryManager.cs b/OpenMetaverse/InventoryManager.cs index c8248ec3..0710f4d0 100644 --- a/OpenMetaverse/InventoryManager.cs +++ b/OpenMetaverse/InventoryManager.cs @@ -361,7 +361,7 @@ namespace OpenMetaverse writer.WriteLine("\tname\t{0}|", Name); writer.WriteLine("\tdesc\t{0}|", Description); - writer.WriteLine("\tcreation_date\t{0}", Helpers.DateTimeToUnixTime(CreationDate)); + writer.WriteLine("\tcreation_date\t{0}", Utils.DateTimeToUnixTime(CreationDate)); writer.WriteLine('}'); } @@ -403,7 +403,7 @@ namespace OpenMetaverse item.Name = rawName.Substring(0, rawName.LastIndexOf('|')); string rawDesc = invItem.Nested["desc"].Value; item.Description = rawDesc.Substring(0, rawDesc.LastIndexOf('|')); - item.CreationDate = Helpers.UnixTimeToDateTime(uint.Parse(invItem.Nested["creation_date"].Value)); + item.CreationDate = Utils.UnixTimeToDateTime(uint.Parse(invItem.Nested["creation_date"].Value)); // Sale info: TextData saleInfo = invItem.Nested["sale_info"]; @@ -1344,7 +1344,7 @@ namespace OpenMetaverse move.FolderData[0] = new UpdateInventoryFolderPacket.FolderDataBlock(); move.FolderData[0].FolderID = folderID; move.FolderData[0].ParentID = parentID; - move.FolderData[0].Name = Helpers.StringToField(newName); + move.FolderData[0].Name = Utils.StringToBytes(newName); move.FolderData[0].Type = -1; _Network.SendPacket(move); @@ -1405,7 +1405,7 @@ namespace OpenMetaverse move.InventoryData[0] = new MoveInventoryItemPacket.InventoryDataBlock(); move.InventoryData[0].ItemID = itemID; move.InventoryData[0].FolderID = parentID; - move.InventoryData[0].NewName = Helpers.StringToField(newName); + move.InventoryData[0].NewName = Utils.StringToBytes(newName); _Network.SendPacket(move); } @@ -1645,8 +1645,8 @@ namespace OpenMetaverse create.InventoryBlock.Type = (sbyte)type; create.InventoryBlock.InvType = (sbyte)invType; create.InventoryBlock.WearableType = (byte)wearableType; - create.InventoryBlock.Name = Helpers.StringToField(name); - create.InventoryBlock.Description = Helpers.StringToField(description); + create.InventoryBlock.Name = Utils.StringToBytes(name); + create.InventoryBlock.Description = Utils.StringToBytes(description); _Network.SendPacket(create); } @@ -1700,7 +1700,7 @@ namespace OpenMetaverse create.FolderData.FolderID = id; create.FolderData.ParentID = parentID; create.FolderData.Type = (sbyte)preferredType; - create.FolderData.Name = Helpers.StringToField(name); + create.FolderData.Name = Utils.StringToBytes(name); _Network.SendPacket(create); @@ -1829,7 +1829,7 @@ namespace OpenMetaverse copy.InventoryData[i].OldItemID = items[i]; if (newNames != null && !String.IsNullOrEmpty(newNames[i])) - copy.InventoryData[i].NewName = Helpers.StringToField(newNames[i]); + copy.InventoryData[i].NewName = Utils.StringToBytes(newNames[i]); else copy.InventoryData[i].NewName = new byte[0]; } @@ -1902,9 +1902,9 @@ namespace OpenMetaverse UpdateInventoryItemPacket.InventoryDataBlock block = new UpdateInventoryItemPacket.InventoryDataBlock(); block.BaseMask = (uint)item.Permissions.BaseMask; block.CRC = ItemCRC(item); - block.CreationDate = (int)Helpers.DateTimeToUnixTime(item.CreationDate); + block.CreationDate = (int)Utils.DateTimeToUnixTime(item.CreationDate); block.CreatorID = item.CreatorID; - block.Description = Helpers.StringToField(item.Description); + block.Description = Utils.StringToBytes(item.Description); block.EveryoneMask = (uint)item.Permissions.EveryoneMask; block.Flags = (uint)item.Flags; block.FolderID = item.ParentUUID; @@ -1913,7 +1913,7 @@ namespace OpenMetaverse block.GroupOwned = item.GroupOwned; block.InvType = (sbyte)item.InventoryType; block.ItemID = item.UUID; - block.Name = Helpers.StringToField(item.Name); + block.Name = Utils.StringToBytes(item.Name); block.NextOwnerMask = (uint)item.Permissions.NextOwnerMask; block.OwnerID = item.OwnerID; block.OwnerMask = (uint)item.Permissions.OwnerMask; @@ -2042,9 +2042,9 @@ namespace OpenMetaverse add.InventoryData.Flags = (uint)item.Flags; add.InventoryData.SaleType = (byte)item.SaleType; add.InventoryData.SalePrice = item.SalePrice; - add.InventoryData.Name = Helpers.StringToField(item.Name); - add.InventoryData.Description = Helpers.StringToField(item.Description); - add.InventoryData.CreationDate = (int)Helpers.DateTimeToUnixTime(item.CreationDate); + add.InventoryData.Name = Utils.StringToBytes(item.Name); + add.InventoryData.Description = Utils.StringToBytes(item.Description); + add.InventoryData.CreationDate = (int)Utils.DateTimeToUnixTime(item.CreationDate); _Network.SendPacket(add, simulator); @@ -2229,9 +2229,9 @@ namespace OpenMetaverse update.InventoryData.Flags = (uint)item.Flags; update.InventoryData.SaleType = (byte)item.SaleType; update.InventoryData.SalePrice = item.SalePrice; - update.InventoryData.Name = Helpers.StringToField(item.Name); - update.InventoryData.Description = Helpers.StringToField(item.Description); - update.InventoryData.CreationDate = (int)Helpers.DateTimeToUnixTime(item.CreationDate); + update.InventoryData.Name = Utils.StringToBytes(item.Name); + update.InventoryData.Description = Utils.StringToBytes(item.Description); + update.InventoryData.CreationDate = (int)Utils.DateTimeToUnixTime(item.CreationDate); update.InventoryData.CRC = ItemCRC(item); _Network.SendPacket(update); @@ -2296,7 +2296,7 @@ namespace OpenMetaverse { _Client.Assets.OnXferReceived -= xferCallback; - string taskList = Helpers.FieldToUTF8String(assetData); + string taskList = Utils.BytesToString(assetData); ParseTaskInventory(this, taskList, out items, out folders); return; } @@ -2527,7 +2527,7 @@ namespace OpenMetaverse CRC += (uint)iitem.Flags; // Flags CRC += (uint)iitem.InventoryType; // InvType CRC += (uint)iitem.AssetType; // Type - CRC += (uint)Helpers.DateTimeToUnixTime(iitem.CreationDate); // CreationDate + CRC += (uint)Utils.DateTimeToUnixTime(iitem.CreationDate); // CreationDate CRC += (uint)iitem.SalePrice; // SalePrice CRC += (uint)((uint)iitem.SaleType * 0x07073096); // SaleType @@ -2666,7 +2666,7 @@ namespace OpenMetaverse string desc = String.Empty; AssetType assetType = AssetType.Unknown; InventoryType inventoryType = InventoryType.Unknown; - DateTime creationDate = Helpers.Epoch; + DateTime creationDate = Utils.Epoch; uint flags = 0; Permissions perms = Permissions.NoPermissions; SaleType saleType = SaleType.Not; @@ -2712,59 +2712,59 @@ namespace OpenMetaverse { // Deprecated uint val; - if (Helpers.TryParseHex(value, out val)) + if (Utils.TryParseHex(value, out val)) perms.BaseMask = (PermissionMask)val; } else if (key == "base_mask") { uint val; - if (Helpers.TryParseHex(value, out val)) + if (Utils.TryParseHex(value, out val)) perms.BaseMask = (PermissionMask)val; } else if (key == "owner_mask") { uint val; - if (Helpers.TryParseHex(value, out val)) + if (Utils.TryParseHex(value, out val)) perms.OwnerMask = (PermissionMask)val; } else if (key == "group_mask") { uint val; - if (Helpers.TryParseHex(value, out val)) + if (Utils.TryParseHex(value, out val)) perms.GroupMask = (PermissionMask)val; } else if (key == "everyone_mask") { uint val; - if (Helpers.TryParseHex(value, out val)) + if (Utils.TryParseHex(value, out val)) perms.EveryoneMask = (PermissionMask)val; } else if (key == "next_owner_mask") { uint val; - if (Helpers.TryParseHex(value, out val)) + if (Utils.TryParseHex(value, out val)) perms.NextOwnerMask = (PermissionMask)val; } else if (key == "creator_id") { - Helpers.TryParse(value, out creatorID); + UUID.TryParse(value, out creatorID); } else if (key == "owner_id") { - Helpers.TryParse(value, out ownerID); + UUID.TryParse(value, out ownerID); } else if (key == "last_owner_id") { - Helpers.TryParse(value, out lastOwnerID); + UUID.TryParse(value, out lastOwnerID); } else if (key == "group_id") { - Helpers.TryParse(value, out groupID); + UUID.TryParse(value, out groupID); } else if (key == "group_owned") { uint val; - if (Helpers.TryParse(value, out val)) + if (UInt32.TryParse(value, out val)) groupOwned = (val != 0); } } @@ -2794,7 +2794,7 @@ namespace OpenMetaverse } else if (key == "sale_price") { - Helpers.TryParse(value, out salePrice); + Int32.TryParse(value, out salePrice); } } } @@ -2819,7 +2819,7 @@ namespace OpenMetaverse } else if (key == "flags") { - Helpers.TryParse(value, out flags); + UInt32.TryParse(value, out flags); } else if (key == "name") { @@ -2832,8 +2832,8 @@ namespace OpenMetaverse else if (key == "creation_date") { uint timestamp; - if (Helpers.TryParse(value, out timestamp)) - creationDate = Helpers.UnixTimeToDateTime(timestamp); + if (UInt32.TryParse(value, out timestamp)) + creationDate = Utils.UnixTimeToDateTime(timestamp); else Logger.Log("Failed to parse creation_date " + value, Helpers.LogLevel.Warning); } @@ -2968,7 +2968,7 @@ namespace OpenMetaverse UUID folderID = reply.FolderData[i].FolderID; FolderData folder = new FolderData(folderID); folder.ParentUUID = reply.FolderData[i].ParentID; - folder.Name = Helpers.FieldToUTF8String(reply.FolderData[i].Name); + folder.Name = Utils.BytesToString(reply.FolderData[i].Name); folder.PreferredType = (AssetType)reply.FolderData[i].Type; folder.OwnerID = reply.AgentData.OwnerID; folders[i] = folder; @@ -3008,10 +3008,10 @@ namespace OpenMetaverse item.CreatorID = reply.ItemData[i].CreatorID; item.AssetType = (AssetType)reply.ItemData[i].Type; item.AssetUUID = reply.ItemData[i].AssetID; - item.CreationDate = Helpers.UnixTimeToDateTime((uint)reply.ItemData[i].CreationDate); - item.Description = Helpers.FieldToUTF8String(reply.ItemData[i].Description); + item.CreationDate = Utils.UnixTimeToDateTime((uint)reply.ItemData[i].CreationDate); + item.Description = Utils.BytesToString(reply.ItemData[i].Description); item.Flags = reply.ItemData[i].Flags; - item.Name = Helpers.FieldToUTF8String(reply.ItemData[i].Name); + item.Name = Utils.BytesToString(reply.ItemData[i].Name); item.GroupID = reply.ItemData[i].GroupID; item.GroupOwned = reply.ItemData[i].GroupOwned; item.Permissions = new Permissions( @@ -3099,13 +3099,13 @@ namespace OpenMetaverse ItemData item = new ItemData(dataBlock.ItemID, (InventoryType)dataBlock.InvType); item.AssetType = (AssetType)dataBlock.Type; item.AssetUUID = dataBlock.AssetID; - item.CreationDate = Helpers.UnixTimeToDateTime(dataBlock.CreationDate); + item.CreationDate = Utils.UnixTimeToDateTime(dataBlock.CreationDate); item.CreatorID = dataBlock.CreatorID; - item.Description = Helpers.FieldToUTF8String(dataBlock.Description); + item.Description = Utils.BytesToString(dataBlock.Description); item.Flags = dataBlock.Flags; item.GroupID = dataBlock.GroupID; item.GroupOwned = dataBlock.GroupOwned; - item.Name = Helpers.FieldToUTF8String(dataBlock.Name); + item.Name = Utils.BytesToString(dataBlock.Name); item.OwnerID = dataBlock.OwnerID; item.ParentUUID = dataBlock.FolderID; item.Permissions = new Permissions( @@ -3159,7 +3159,7 @@ namespace OpenMetaverse if (OnFolderUpdate != null) { FolderData folderParams = new FolderData(); - folderParams.Name = Helpers.FieldToUTF8String(dataBlock.Name); + folderParams.Name = Utils.BytesToString(dataBlock.Name); folderParams.OwnerID = update.AgentData.AgentID; folderParams.ParentUUID = dataBlock.ParentID; @@ -3178,13 +3178,13 @@ namespace OpenMetaverse ItemData item = new ItemData(dataBlock.ItemID, (InventoryType)dataBlock.InvType); item.AssetType = (AssetType)dataBlock.Type; if (dataBlock.AssetID != UUID.Zero) item.AssetUUID = dataBlock.AssetID; - item.CreationDate = Helpers.UnixTimeToDateTime(dataBlock.CreationDate); + item.CreationDate = Utils.UnixTimeToDateTime(dataBlock.CreationDate); item.CreatorID = dataBlock.CreatorID; - item.Description = Helpers.FieldToUTF8String(dataBlock.Description); + item.Description = Utils.BytesToString(dataBlock.Description); item.Flags = dataBlock.Flags; item.GroupID = dataBlock.GroupID; item.GroupOwned = dataBlock.GroupOwned; - item.Name = Helpers.FieldToUTF8String(dataBlock.Name); + item.Name = Utils.BytesToString(dataBlock.Name); item.OwnerID = dataBlock.OwnerID; item.ParentUUID = dataBlock.FolderID; item.Permissions = new Permissions( @@ -3243,13 +3243,13 @@ namespace OpenMetaverse item.InventoryType = (InventoryType)dataBlock.InvType; item.AssetType = (AssetType)dataBlock.Type; item.AssetUUID = dataBlock.AssetID; - item.CreationDate = Helpers.UnixTimeToDateTime(dataBlock.CreationDate); + item.CreationDate = Utils.UnixTimeToDateTime(dataBlock.CreationDate); item.CreatorID = dataBlock.CreatorID; - item.Description = Helpers.FieldToUTF8String(dataBlock.Description); + item.Description = Utils.BytesToString(dataBlock.Description); item.Flags = dataBlock.Flags; item.GroupID = dataBlock.GroupID; item.GroupOwned = dataBlock.GroupOwned; - item.Name = Helpers.FieldToUTF8String(dataBlock.Name); + item.Name = Utils.BytesToString(dataBlock.Name); item.OwnerID = dataBlock.OwnerID; item.ParentUUID = dataBlock.FolderID; item.Permissions = new Permissions( @@ -3297,7 +3297,7 @@ namespace OpenMetaverse try { OnTaskInventoryReply(reply.InventoryData.TaskID, reply.InventoryData.Serial, - Helpers.FieldToUTF8String(reply.InventoryData.Filename)); + Utils.BytesToString(reply.InventoryData.Filename)); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, _Client, e); } } @@ -3355,7 +3355,7 @@ namespace OpenMetaverse imp.MessageBlock.Offline = 0; imp.MessageBlock.ID = im.IMSessionID; imp.MessageBlock.Timestamp = 0; - imp.MessageBlock.FromAgentName = Helpers.StringToField(_Agents.Name); + imp.MessageBlock.FromAgentName = Utils.StringToBytes(_Agents.Name); imp.MessageBlock.Message = new byte[0]; imp.MessageBlock.ParentEstateID = 0; imp.MessageBlock.RegionID = UUID.Zero; diff --git a/OpenMetaverse/LLSD/BinaryLLSD.cs b/OpenMetaverse/LLSD/BinaryLLSD.cs index ce39cf8b..bb4d55cf 100644 --- a/OpenMetaverse/LLSD/BinaryLLSD.cs +++ b/OpenMetaverse/LLSD/BinaryLLSD.cs @@ -274,7 +274,7 @@ using System.Text; break; case dateBinaryMarker: double timestamp = NetworkToHostDouble( ConsumeBytes( stream, doubleLength )); - DateTime dateTime = DateTime.SpecifyKind( Helpers.Epoch, DateTimeKind.Utc ); + DateTime dateTime = DateTime.SpecifyKind( Utils.Epoch, DateTimeKind.Utc ); dateTime = dateTime.AddSeconds(timestamp); llsd = LLSD.FromDate( dateTime.ToLocalTime() ); break; diff --git a/OpenMetaverse/LLSD/LLSD.cs b/OpenMetaverse/LLSD/LLSD.cs index 3f4e1f02..812dc44c 100644 --- a/OpenMetaverse/LLSD/LLSD.cs +++ b/OpenMetaverse/LLSD/LLSD.cs @@ -80,9 +80,10 @@ namespace OpenMetaverse.StructuredData public virtual double AsReal() { return 0d; } public virtual string AsString() { return String.Empty; } public virtual UUID AsUUID() { return UUID.Zero; } - public virtual DateTime AsDate() { return Helpers.Epoch; } + public virtual DateTime AsDate() { return Utils.Epoch; } public virtual Uri AsUri() { return new Uri(String.Empty); } public virtual byte[] AsBinary() { return new byte[0]; } + public override string ToString() { return "undef"; } public static LLSD FromBoolean(bool value) { return new LLSDBoolean(value); } @@ -101,6 +102,63 @@ namespace OpenMetaverse.StructuredData public static LLSD FromBinary(byte[] value) { return new LLSDBinary(value); } public static LLSD FromBinary(long value) { return new LLSDBinary(value); } public static LLSD FromBinary(ulong value) { return new LLSDBinary(value); } + + public static LLSD FromVector2(Vector2 value) + { + LLSDArray array = new LLSDArray(); + array.Add(LLSD.FromReal(value.X)); + array.Add(LLSD.FromReal(value.Y)); + return array; + } + + public static LLSD FromVector3(Vector3 value) + { + LLSDArray array = new LLSDArray(); + array.Add(LLSD.FromReal(value.X)); + array.Add(LLSD.FromReal(value.Y)); + array.Add(LLSD.FromReal(value.Z)); + return array; + } + + public static LLSD FromVector3d(Vector3d value) + { + LLSDArray array = new LLSDArray(); + array.Add(LLSD.FromReal(value.X)); + array.Add(LLSD.FromReal(value.Y)); + array.Add(LLSD.FromReal(value.Z)); + return array; + } + + public static LLSD FromVector4(Vector4 value) + { + LLSDArray array = new LLSDArray(); + array.Add(LLSD.FromReal(value.X)); + array.Add(LLSD.FromReal(value.Y)); + array.Add(LLSD.FromReal(value.Z)); + array.Add(LLSD.FromReal(value.W)); + return array; + } + + public static LLSD FromQuaternion(Quaternion value) + { + LLSDArray array = new LLSDArray(); + array.Add(LLSD.FromReal(value.X)); + array.Add(LLSD.FromReal(value.Y)); + array.Add(LLSD.FromReal(value.Z)); + array.Add(LLSD.FromReal(value.W)); + return array; + } + + public static LLSD FromColor4(Color4 value) + { + LLSDArray array = new LLSDArray(); + array.Add(LLSD.FromReal(value.R)); + array.Add(LLSD.FromReal(value.G)); + array.Add(LLSD.FromReal(value.B)); + array.Add(LLSD.FromReal(value.A)); + return array; + } + public static LLSD FromObject(object value) { if (value == null) { return new LLSD(); } @@ -120,6 +178,12 @@ namespace OpenMetaverse.StructuredData else if (value is byte[]) { return new LLSDBinary((byte[])value); } else if (value is long) { return new LLSDBinary((long)value); } else if (value is ulong) { return new LLSDBinary((ulong)value); } + else if (value is Vector2) { return FromVector2((Vector2)value); } + else if (value is Vector3) { return FromVector3((Vector3)value); } + else if (value is Vector3d) { return FromVector3d((Vector3d)value); } + else if (value is Vector4) { return FromVector4((Vector4)value); } + else if (value is Quaternion) { return FromQuaternion((Quaternion)value); } + else if (value is Color4) { return FromColor4((Color4)value); } else return new LLSD(); } } @@ -249,7 +313,7 @@ namespace OpenMetaverse.StructuredData public override int AsInteger() { double dbl; - if (Helpers.TryParse(value, out dbl)) + if (Double.TryParse(value, out dbl)) return (int)Math.Floor( dbl ); else return 0; @@ -257,7 +321,7 @@ namespace OpenMetaverse.StructuredData public override double AsReal() { double dbl; - if (Helpers.TryParse(value, out dbl)) + if (Double.TryParse(value, out dbl)) return dbl; else return 0d; @@ -278,7 +342,7 @@ namespace OpenMetaverse.StructuredData if (DateTime.TryParse(value, out dt)) return dt; else - return Helpers.Epoch; + return Utils.Epoch; } public override Uri AsUri() { return new Uri(value); } @@ -547,6 +611,92 @@ namespace OpenMetaverse.StructuredData this.value = new List(); } + public Vector2 AsVector2() + { + Vector2 vector = Vector2.Zero; + + if (this.Count == 2) + { + vector.X = (float)this[0].AsReal(); + vector.Y = (float)this[1].AsReal(); + } + + return vector; + } + + public Vector3 AsVector3() + { + Vector3 vector = Vector3.Zero; + + if (this.Count == 3) + { + vector.X = (float)this[0].AsReal(); + vector.Y = (float)this[1].AsReal(); + vector.Z = (float)this[2].AsReal(); + } + + return vector; + } + + public Vector3d AsVector3d() + { + Vector3d vector = Vector3d.Zero; + + if (this.Count == 3) + { + vector.X = this[0].AsReal(); + vector.Y = this[1].AsReal(); + vector.Z = this[2].AsReal(); + } + + return vector; + } + + public Vector4 AsVector4() + { + Vector4 vector = Vector4.Zero; + + if (this.Count == 4) + { + vector.X = (float)this[0].AsReal(); + vector.Y = (float)this[1].AsReal(); + vector.Z = (float)this[2].AsReal(); + vector.W = (float)this[3].AsReal(); + } + + return vector; + } + + public Quaternion AsQuaternion() + { + Quaternion quaternion = Quaternion.Identity; + + if (this.Count == 4) + { + quaternion.X = (float)this[0].AsReal(); + quaternion.Y = (float)this[1].AsReal(); + quaternion.Z = (float)this[2].AsReal(); + quaternion.W = (float)this[3].AsReal(); + } + + return quaternion; + } + + public Color4 AsColor4() + { + Color4 color = Color4.Black; + + if (this.Count == 4) + { + color.R = (float)this[0].AsReal(); + color.G = (float)this[1].AsReal(); + color.B = (float)this[2].AsReal(); + color.A = (float)this[3].AsReal(); + } + + return color; + } + public override bool AsBoolean() { return value.Count > 0; } public override string ToString() diff --git a/OpenMetaverse/LLSD/NotationLLSD.cs b/OpenMetaverse/LLSD/NotationLLSD.cs index dd9f3bda..f4a220c1 100644 --- a/OpenMetaverse/LLSD/NotationLLSD.cs +++ b/OpenMetaverse/LLSD/NotationLLSD.cs @@ -287,7 +287,7 @@ namespace OpenMetaverse.StructuredData throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in date."); string date = GetStringDelimitedBy(reader, doubleQuotesNotationMarker); DateTime dt; - if (!Helpers.TryParse(date, out dt)) + if (!DateTime.TryParse(date, out dt)) throw new LLSDException("Notation LLSD parsing: Invalid date discovered."); llsd = LLSD.FromDate(dt); break; @@ -320,7 +320,7 @@ namespace OpenMetaverse.StructuredData reader.Read(); } int integer; - if (!Helpers.TryParse(s.ToString(), out integer)) + if (!Int32.TryParse(s.ToString(), out integer)) throw new LLSDException("Notation LLSD parsing: Can't parse integer value." + s.ToString()); return LLSD.FromInteger(integer); @@ -345,7 +345,7 @@ namespace OpenMetaverse.StructuredData reader.Read(); } double dbl; - if (!Helpers.TryParse(s.ToString(), out dbl)) + if (!Utils.TryParseDouble(s.ToString(), out dbl)) throw new LLSDException("Notation LLSD parsing: Can't parse real value: " + s.ToString()); return LLSD.FromReal(dbl); @@ -677,7 +677,7 @@ namespace OpenMetaverse.StructuredData if (character < 0) throw new LLSDException("Notation LLSD parsing: Can't parse length value cause unexpected end of stream."); int length; - if (!Helpers.TryParse(s.ToString(), out length)) + if (!Int32.TryParse(s.ToString(), out length)) throw new LLSDException("Notation LLSD parsing: Can't parse length value."); return length; diff --git a/OpenMetaverse/LLSD/XmlLLSD.cs b/OpenMetaverse/LLSD/XmlLLSD.cs index 18b3e73d..f4ac3f3c 100644 --- a/OpenMetaverse/LLSD/XmlLLSD.cs +++ b/OpenMetaverse/LLSD/XmlLLSD.cs @@ -60,7 +60,7 @@ namespace OpenMetaverse.StructuredData /// public static LLSD DeserializeXml(string xmlData) { - byte[] bytes = Helpers.StringToField(xmlData); + byte[] bytes = Utils.StringToBytes(xmlData); return DeserializeXml(new XmlTextReader(new MemoryStream(bytes, false))); } @@ -294,7 +294,7 @@ namespace OpenMetaverse.StructuredData if (reader.Read()) { int value = 0; - Helpers.TryParse(reader.ReadString().Trim(), out value); + Int32.TryParse(reader.ReadString().Trim(), out value); ret = LLSD.FromInteger(value); break; } @@ -316,7 +316,7 @@ namespace OpenMetaverse.StructuredData if (str == "nan") value = Double.NaN; else - Helpers.TryParse(str, out value); + Utils.TryParseDouble(str, out value); ret = LLSD.FromReal(value); break; @@ -345,18 +345,18 @@ namespace OpenMetaverse.StructuredData if (reader.IsEmptyElement) { reader.Read(); - return LLSD.FromDate(Helpers.Epoch); + return LLSD.FromDate(Utils.Epoch); } if (reader.Read()) { - DateTime value = Helpers.Epoch; - Helpers.TryParse(reader.ReadString().Trim(), out value); + DateTime value = Utils.Epoch; + DateTime.TryParse(reader.ReadString().Trim(), out value); ret = LLSD.FromDate(value); break; } - ret = LLSD.FromDate(Helpers.Epoch); + ret = LLSD.FromDate(Utils.Epoch); break; case "string": if (reader.IsEmptyElement) diff --git a/OpenMetaverse/Login.cs b/OpenMetaverse/Login.cs index 8599a4eb..297aaaa4 100644 --- a/OpenMetaverse/Login.cs +++ b/OpenMetaverse/Login.cs @@ -201,7 +201,7 @@ namespace OpenMetaverse } } - SecondsSinceEpoch = Helpers.UnixTimeToDateTime(ParseUInt("seconds_since_epoch", reply)); + SecondsSinceEpoch = Utils.UnixTimeToDateTime(ParseUInt("seconds_since_epoch", reply)); InventoryRoot = ParseMappedUUID("inventory-root", "folder_id", reply); InventoryFolders = ParseInventoryFolders("inventory-skeleton", AgentID, reply); LibraryRoot = ParseMappedUUID("inventory-lib-root", "folder_id", reply); @@ -245,16 +245,12 @@ namespace OpenMetaverse { if (llsd.Type == LLSDType.Array) { - Vector3 vec = new Vector3(); - vec.FromLLSD(llsd); - return vec; + return ((LLSDArray)llsd).AsVector3(); } else if (llsd.Type == LLSDType.String) { LLSDArray array = (LLSDArray)LLSDParser.DeserializeNotation(llsd.AsString()); - Vector3 vec = new Vector3(); - vec.FromLLSD(array); - return vec; + return array.AsVector3(); } } @@ -552,7 +548,7 @@ namespace OpenMetaverse // Convert the password to MD5 if it isn't already if (loginParams.Password.Length != 35 && !loginParams.Password.StartsWith("$1$")) - loginParams.Password = Helpers.MD5(loginParams.Password); + loginParams.Password = Utils.MD5(loginParams.Password); // Override SSL authentication mechanisms. DO NOT convert this to the // .NET 2.0 preferred method, the equivalent function in Mono has a diff --git a/OpenMetaverse/MathHelper.cs b/OpenMetaverse/MathHelper.cs deleted file mode 100644 index 12b5bb3f..00000000 --- a/OpenMetaverse/MathHelper.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; - -namespace OpenMetaverse -{ - public static class MathHelper - { - public const float E = (float)Math.E; - public const float LOG10E = 0.4342945f; - public const float LOG2E = 1.442695f; - public const float PI = (float)Math.PI; - public const float TWO_PI = (float)(Math.PI * 2.0d); - public const float PI_OVER_TWO = (float)(Math.PI / 2.0d); - public const float PI_OVER_FOUR = (float)(Math.PI / 4.0d); - - /// - /// Clamp a given value between a range - /// - /// Value to clamp - /// Minimum allowable value - /// Maximum allowable value - /// A value inclusively between lower and upper - public static float Clamp(float value, float min, float max) - { - // First we check to see if we're greater than the max - value = (value > max) ? max : value; - - // Then we check to see if we're less than the min. - value = (value < min) ? min : value; - - // There's no check to see if min > max. - return value; - } - - /// - /// Clamp a given value between a range - /// - /// Value to clamp - /// Minimum allowable value - /// Maximum allowable value - /// A value inclusively between lower and upper - public static double Clamp(double value, double min, double max) - { - // First we check to see if we're greater than the max - value = (value > max) ? max : value; - - // Then we check to see if we're less than the min. - value = (value < min) ? min : value; - - // There's no check to see if min > max. - return value; - } - - /// - /// Round a floating-point value to the nearest integer - /// - /// Floating point number to round - /// Integer - public static int Round(float val) - { - return (int)Math.Floor(val + 0.5f); - } - - /// - /// Test if a single precision float is a finite number - /// - public static bool IsFinite(float value) - { - return !(Single.IsNaN(value) || Single.IsInfinity(value)); - } - - /// - /// Test if a double precision float is a finite number - /// - public static bool IsFinite(double value) - { - return !(Double.IsNaN(value) || Double.IsInfinity(value)); - } - - /// - /// Get the distance between two floating-point values - /// - /// First value - /// Second value - /// The distance between the two values - public static float Distance(float value1, float value2) - { - return Math.Abs(value1 - value2); - } - - public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) - { - // All transformed to double not to lose precission - // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity - double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; - double sCubed = s * s * s; - double sSquared = s * s; - - if (amount == 0f) - result = value1; - else if (amount == 1f) - result = value2; - else - result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + - (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + - t1 * s + v1; - return (float)result; - } - - public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount) - { - // All transformed to double not to lose precission - // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity - double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; - double sCubed = s * s * s; - double sSquared = s * s; - - if (amount == 0d) - result = value1; - else if (amount == 1f) - result = value2; - else - result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + - (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + - t1 * s + v1; - return result; - } - - public static float Lerp(float value1, float value2, float amount) - { - return value1 + (value2 - value1) * amount; - } - - public static double Lerp(double value1, double value2, double amount) - { - return value1 + (value2 - value1) * amount; - } - - public static float SmoothStep(float value1, float value2, float amount) - { - // It is expected that 0 < amount < 1 - // If amount < 0, return value1 - // If amount > 1, return value2 - float result = MathHelper.Clamp(amount, 0f, 1f); - return MathHelper.Hermite(value1, 0f, value2, 0f, result); - } - - public static double SmoothStep(double value1, double value2, double amount) - { - // It is expected that 0 < amount < 1 - // If amount < 0, return value1 - // If amount > 1, return value2 - double result = MathHelper.Clamp(amount, 0f, 1f); - return MathHelper.Hermite(value1, 0f, value2, 0f, result); - } - - public static float ToDegrees(float radians) - { - // This method uses double precission internally, - // though it returns single float - // Factor = 180 / pi - return (float)(radians * 57.295779513082320876798154814105); - } - - public static float ToRadians(float degrees) - { - // This method uses double precission internally, - // though it returns single float - // Factor = pi / 180 - return (float)(degrees * 0.017453292519943295769236907684886); - } - } -} diff --git a/OpenMetaverse/NameValue.cs b/OpenMetaverse/NameValue.cs index 1e3832ac..3a686975 100644 --- a/OpenMetaverse/NameValue.cs +++ b/OpenMetaverse/NameValue.cs @@ -212,35 +212,35 @@ namespace OpenMetaverse case ValueType.F32: { float temp; - Helpers.TryParse(value, out temp); + Utils.TryParseSingle(value, out temp); Value = temp; break; } case ValueType.S32: { int temp; - Helpers.TryParse(value, out temp); + Int32.TryParse(value, out temp); Value = temp; break; } case ValueType.U32: { uint temp; - Helpers.TryParse(value, out temp); + UInt32.TryParse(value, out temp); Value = temp; break; } case ValueType.U64: { ulong temp; - Helpers.TryParse(value, out temp); + UInt64.TryParse(value, out temp); Value = temp; break; } case ValueType.VEC3: { Vector3 temp; - Helpers.TryParse(value, out temp); + Vector3.TryParse(value, out temp); Value = temp; break; } diff --git a/OpenMetaverse/NetworkManager.cs b/OpenMetaverse/NetworkManager.cs index a15a96d2..9b649e72 100644 --- a/OpenMetaverse/NetworkManager.cs +++ b/OpenMetaverse/NetworkManager.cs @@ -1046,7 +1046,7 @@ namespace OpenMetaverse simulator.ID = handshake.RegionInfo.CacheID; simulator.IsEstateManager = handshake.RegionInfo.IsEstateManager; - simulator.Name = Helpers.FieldToUTF8String(handshake.RegionInfo.SimName); + simulator.Name = Utils.BytesToString(handshake.RegionInfo.SimName); simulator.SimOwner = handshake.RegionInfo.SimOwner; simulator.TerrainBase0 = handshake.RegionInfo.TerrainBase0; simulator.TerrainBase1 = handshake.RegionInfo.TerrainBase1; @@ -1134,7 +1134,7 @@ namespace OpenMetaverse private void KickUserHandler(Packet packet, Simulator simulator) { - string message = Helpers.FieldToUTF8String(((KickUserPacket)packet).UserInfo.Reason); + string message = Utils.BytesToString(((KickUserPacket)packet).UserInfo.Reason); // Fire the callback to let client apps know we are shutting down if (OnDisconnected != null) diff --git a/OpenMetaverse/ObjectManager.cs b/OpenMetaverse/ObjectManager.cs index 3d5ad9d2..df524a8a 100644 --- a/OpenMetaverse/ObjectManager.cs +++ b/OpenMetaverse/ObjectManager.cs @@ -880,7 +880,7 @@ namespace OpenMetaverse image.ObjectData[0] = new ObjectImagePacket.ObjectDataBlock(); image.ObjectData[0].ObjectLocalID = localID; image.ObjectData[0].TextureEntry = textures.ToBytes(); - image.ObjectData[0].MediaURL = Helpers.StringToField(mediaUrl); + image.ObjectData[0].MediaURL = Utils.StringToBytes(mediaUrl); Client.Network.SendPacket(image, simulator); } @@ -1077,7 +1077,7 @@ namespace OpenMetaverse { namePacket.ObjectData[i] = new ObjectNamePacket.ObjectDataBlock(); namePacket.ObjectData[i].LocalID = localIDs[i]; - namePacket.ObjectData[i].Name = Helpers.StringToField(names[i]); + namePacket.ObjectData[i].Name = Utils.StringToBytes(names[i]); } Client.Network.SendPacket(namePacket, simulator); @@ -1112,7 +1112,7 @@ namespace OpenMetaverse { descPacket.ObjectData[i] = new ObjectDescriptionPacket.ObjectDataBlock(); descPacket.ObjectData[i].LocalID = localIDs[i]; - descPacket.ObjectData[i].Description = Helpers.StringToField(descriptions[i]); + descPacket.ObjectData[i].Description = Utils.StringToBytes(descriptions[i]); } Client.Network.SendPacket(descPacket, simulator); @@ -1442,7 +1442,7 @@ namespace OpenMetaverse #region NameValue parsing - string nameValue = Helpers.FieldToUTF8String(block.NameValue); + string nameValue = Utils.BytesToString(block.NameValue); if (nameValue.Length > 0) { string[] lines = nameValue.Split('\n'); @@ -1636,8 +1636,8 @@ namespace OpenMetaverse prim.Scale = block.Scale; prim.ClickAction = (ClickAction)block.ClickAction; prim.OwnerID = block.OwnerID; - prim.MediaURL = Helpers.FieldToUTF8String(block.MediaURL); - prim.Text = Helpers.FieldToUTF8String(block.Text); + prim.MediaURL = Utils.BytesToString(block.MediaURL); + prim.Text = Utils.BytesToString(block.Text); prim.TextColor = new Color4(block.TextColor, 0, false, true); // Sound information @@ -2332,21 +2332,21 @@ namespace OpenMetaverse props.Category = objectData.Category; props.CreationDate = objectData.CreationDate; props.CreatorID = objectData.CreatorID; - props.Description = Helpers.FieldToUTF8String(objectData.Description); + props.Description = Utils.BytesToString(objectData.Description); props.FolderID = objectData.FolderID; props.FromTaskID = objectData.FromTaskID; props.GroupID = objectData.GroupID; props.InventorySerial = objectData.InventorySerial; props.ItemID = objectData.ItemID; props.LastOwnerID = objectData.LastOwnerID; - props.Name = Helpers.FieldToUTF8String(objectData.Name); + props.Name = Utils.BytesToString(objectData.Name); props.ObjectID = objectData.ObjectID; props.OwnerID = objectData.OwnerID; props.OwnershipCost = objectData.OwnershipCost; props.SalePrice = objectData.SalePrice; props.SaleType = objectData.SaleType; - props.SitName = Helpers.FieldToUTF8String(objectData.SitName); - props.TouchName = Helpers.FieldToUTF8String(objectData.TouchName); + props.SitName = Utils.BytesToString(objectData.SitName); + props.TouchName = Utils.BytesToString(objectData.TouchName); int numTextures = objectData.TextureID.Length / 16; props.TextureIDs = new UUID[numTextures]; @@ -2379,10 +2379,10 @@ namespace OpenMetaverse props.RequestFlags = (LLObject.ObjectPropertiesFamily.RequestFlagsType)op.ObjectData.RequestFlags; props.Category = op.ObjectData.Category; - props.Description = Helpers.FieldToUTF8String(op.ObjectData.Description); + props.Description = Utils.BytesToString(op.ObjectData.Description); props.GroupID = op.ObjectData.GroupID; props.LastOwnerID = op.ObjectData.LastOwnerID; - props.Name = Helpers.FieldToUTF8String(op.ObjectData.Name); + props.Name = Utils.BytesToString(op.ObjectData.Name); props.ObjectID = op.ObjectData.ObjectID; props.OwnerID = op.ObjectData.OwnerID; props.OwnershipCost = op.ObjectData.OwnershipCost; diff --git a/OpenMetaverse/ParcelManager.cs b/OpenMetaverse/ParcelManager.cs index 1f1736a3..644882f4 100644 --- a/OpenMetaverse/ParcelManager.cs +++ b/OpenMetaverse/ParcelManager.cs @@ -387,7 +387,7 @@ namespace OpenMetaverse OwnerID = UUID.Zero; IsGroupOwned = false; AuctionID = 0; - ClaimDate = Helpers.Epoch; + ClaimDate = Utils.Epoch; ClaimPrice = 0; RentPrice = 0; AABBMin = Vector3.Zero; @@ -445,15 +445,15 @@ namespace OpenMetaverse request.ParcelData.AuthBuyerID = this.AuthBuyerID; request.ParcelData.Category = (byte)this.Category; - request.ParcelData.Desc = Helpers.StringToField(this.Desc); + request.ParcelData.Desc = Utils.StringToBytes(this.Desc); request.ParcelData.GroupID = this.GroupID; request.ParcelData.LandingType = this.LandingType; request.ParcelData.MediaAutoScale = this.Media.MediaAutoScale; request.ParcelData.MediaID = this.Media.MediaID; - request.ParcelData.MediaURL = Helpers.StringToField(this.Media.MediaURL); - request.ParcelData.MusicURL = Helpers.StringToField(this.MusicURL); - request.ParcelData.Name = Helpers.StringToField(this.Name); + request.ParcelData.MediaURL = Utils.StringToBytes(this.Media.MediaURL); + request.ParcelData.MusicURL = Utils.StringToBytes(this.MusicURL); + request.ParcelData.Name = Utils.StringToBytes(this.Name); if (wantReply) request.ParcelData.Flags = 1; request.ParcelData.ParcelFlags = (uint)this.Flags; request.ParcelData.PassHours = this.PassHours; @@ -1348,17 +1348,17 @@ namespace OpenMetaverse parcelInfo.ActualArea = info.Data.ActualArea; parcelInfo.AuctionID = info.Data.AuctionID; parcelInfo.BillableArea = info.Data.BillableArea; - parcelInfo.Description = Helpers.FieldToUTF8String(info.Data.Desc); + parcelInfo.Description = Utils.BytesToString(info.Data.Desc); parcelInfo.Dwell = info.Data.Dwell; parcelInfo.GlobalX = info.Data.GlobalX; parcelInfo.GlobalY = info.Data.GlobalY; parcelInfo.GlobalZ = info.Data.GlobalZ; parcelInfo.ID = info.Data.ParcelID; parcelInfo.Mature = ((info.Data.Flags & 1) != 0) ? true : false; - parcelInfo.Name = Helpers.FieldToUTF8String(info.Data.Name); + parcelInfo.Name = Utils.BytesToString(info.Data.Name); parcelInfo.OwnerID = info.Data.OwnerID; parcelInfo.SalePrice = info.Data.SalePrice; - parcelInfo.SimName = Helpers.FieldToUTF8String(info.Data.SimName); + parcelInfo.SimName = Utils.BytesToString(info.Data.SimName); parcelInfo.SnapshotID = info.Data.SnapshotID; try { OnParcelInfo(parcelInfo); } @@ -1384,14 +1384,14 @@ namespace OpenMetaverse Parcel parcel = new Parcel(simulator, parcelDataBlock["LocalID"].AsInteger()); - parcel.AABBMax.FromLLSD(parcelDataBlock["AABBMax"]); - parcel.AABBMin.FromLLSD(parcelDataBlock["AABBMin"]); + parcel.AABBMax = ((LLSDArray)parcelDataBlock["AABBMax"]).AsVector3(); + parcel.AABBMin = ((LLSDArray)parcelDataBlock["AABBMin"]).AsVector3(); parcel.Area = parcelDataBlock["Area"].AsInteger(); parcel.AuctionID = (uint)parcelDataBlock["AuctionID"].AsInteger(); parcel.AuthBuyerID = parcelDataBlock["AuthBuyerID"].AsUUID(); parcel.Bitmap = parcelDataBlock["Bitmap"].AsBinary(); parcel.Category = (Parcel.ParcelCategory)parcelDataBlock["Category"].AsInteger(); - parcel.ClaimDate = Helpers.UnixTimeToDateTime((uint)parcelDataBlock["ClaimDate"].AsInteger()); + parcel.ClaimDate = Utils.UnixTimeToDateTime((uint)parcelDataBlock["ClaimDate"].AsInteger()); parcel.ClaimPrice = parcelDataBlock["ClaimPrice"].AsInteger(); parcel.Desc = parcelDataBlock["Desc"].AsString(); @@ -1436,8 +1436,8 @@ namespace OpenMetaverse parcel.SnapshotID = parcelDataBlock["SnapshotID"].AsUUID(); parcel.Status = (Parcel.ParcelStatus)parcelDataBlock["Status"].AsInteger(); parcel.TotalPrims = parcelDataBlock["TotalPrims"].AsInteger(); - parcel.UserLocation.FromLLSD(parcelDataBlock["UserLocation"]); - parcel.UserLookAt.FromLLSD(parcelDataBlock["UserLookAt"]); + parcel.UserLocation = ((LLSDArray)parcelDataBlock["UserLocation"]).AsVector3(); + parcel.UserLookAt = ((LLSDArray)parcelDataBlock["UserLookAt"]).AsVector3(); parcel.Media.MediaDesc = mediaDataBlock["MediaDesc"].AsString(); parcel.Media.MediaHeight = mediaDataBlock["MediaHeight"].AsInteger(); parcel.Media.MediaWidth = mediaDataBlock["MediaWidth"].AsInteger(); @@ -1519,10 +1519,10 @@ namespace OpenMetaverse parcel.AuthBuyerID = properties.ParcelData.AuthBuyerID; parcel.Bitmap = properties.ParcelData.Bitmap; parcel.Category = (Parcel.ParcelCategory)(sbyte)properties.ParcelData.Category; - parcel.ClaimDate = Helpers.UnixTimeToDateTime((uint)properties.ParcelData.ClaimDate); + parcel.ClaimDate = Utils.UnixTimeToDateTime((uint)properties.ParcelData.ClaimDate); // ClaimPrice seems to always be zero? parcel.ClaimPrice = properties.ParcelData.ClaimPrice; - parcel.Desc = Helpers.FieldToUTF8String(properties.ParcelData.Desc); + parcel.Desc = Utils.BytesToString(properties.ParcelData.Desc); parcel.GroupID = properties.ParcelData.GroupID; parcel.GroupPrims = properties.ParcelData.GroupPrims; parcel.IsGroupOwned = properties.ParcelData.IsGroupOwned; @@ -1530,9 +1530,9 @@ namespace OpenMetaverse parcel.MaxPrims = properties.ParcelData.MaxPrims; parcel.Media.MediaAutoScale = properties.ParcelData.MediaAutoScale; parcel.Media.MediaID = properties.ParcelData.MediaID; - parcel.Media.MediaURL = Helpers.FieldToUTF8String(properties.ParcelData.MediaURL); - parcel.MusicURL = Helpers.FieldToUTF8String(properties.ParcelData.MusicURL); - parcel.Name = Helpers.FieldToUTF8String(properties.ParcelData.Name); + parcel.Media.MediaURL = Utils.BytesToString(properties.ParcelData.MediaURL); + parcel.MusicURL = Utils.BytesToString(properties.ParcelData.MusicURL); + parcel.Name = Utils.BytesToString(properties.ParcelData.Name); parcel.OtherCleanTime = properties.ParcelData.OtherCleanTime; parcel.OtherCount = properties.ParcelData.OtherCount; parcel.OtherPrims = properties.ParcelData.OtherPrims; @@ -1628,7 +1628,7 @@ namespace OpenMetaverse ParcelAccessEntry pae = new ParcelAccessEntry(); pae.AgentID = reply.List[i].ID; pae.Flags = (AccessList)reply.List[i].Flags; - pae.Time = Helpers.UnixTimeToDateTime((uint)reply.List[i].Time); + pae.Time = Utils.UnixTimeToDateTime((uint)reply.List[i].Time); accessList.Add(pae); } @@ -1702,12 +1702,12 @@ namespace OpenMetaverse media.MediaAutoScale = reply.DataBlock.MediaAutoScale; media.MediaID = reply.DataBlock.MediaID; - media.MediaDesc = Helpers.FieldToUTF8String(reply.DataBlockExtended.MediaDesc); + media.MediaDesc = Utils.BytesToString(reply.DataBlockExtended.MediaDesc); media.MediaHeight = reply.DataBlockExtended.MediaHeight; media.MediaLoop = ((reply.DataBlockExtended.MediaLoop & 1) != 0) ? true : false; - media.MediaType = Helpers.FieldToUTF8String(reply.DataBlockExtended.MediaType); + media.MediaType = Utils.BytesToString(reply.DataBlockExtended.MediaType); media.MediaWidth = reply.DataBlockExtended.MediaWidth; - media.MediaURL = Helpers.FieldToUTF8String(reply.DataBlock.MediaURL); + media.MediaURL = Utils.BytesToString(reply.DataBlock.MediaURL); if (OnParcelMediaUpdate != null) { diff --git a/OpenMetaverse/Prims.cs b/OpenMetaverse/Prims.cs index 87c8f8b8..87ec8a6b 100644 --- a/OpenMetaverse/Prims.cs +++ b/OpenMetaverse/Prims.cs @@ -294,7 +294,7 @@ namespace OpenMetaverse map["air_friction"] = LLSD.FromReal(Drag); map["wind_sensitivity"] = LLSD.FromReal(Wind); map["tension"] = LLSD.FromReal(Tension); - map["user_force"] = Force.GetLLSD(); + map["user_force"] = LLSD.FromVector3(Force); return map; } @@ -312,7 +312,7 @@ namespace OpenMetaverse flex.Drag = (float)map["air_friction"].AsReal(); flex.Wind = (float)map["wind_sensitivity"].AsReal(); flex.Tension = (float)map["tension"].AsReal(); - flex.Force.FromLLSD(map["user_force"]); + flex.Force = ((LLSDArray)map["user_force"]).AsVector3(); } return flex; @@ -386,7 +386,7 @@ namespace OpenMetaverse { LLSDMap map = new LLSDMap(); - map["color"] = Color.GetLLSD(); + map["color"] = LLSD.FromColor4(Color); map["intensity"] = LLSD.FromReal(Intensity); map["radius"] = LLSD.FromReal(Radius); map["cutoff"] = LLSD.FromReal(Cutoff); @@ -403,7 +403,7 @@ namespace OpenMetaverse { LLSDMap map = (LLSDMap)llsd; - light.Color.FromLLSD(map["color"]); + light.Color = ((LLSDArray)map["color"]).AsColor4(); light.Intensity = (float)map["intensity"].AsReal(); light.Radius = (float)map["radius"].AsReal(); light.Cutoff = (float)map["cutoff"].AsReal(); @@ -571,9 +571,9 @@ namespace OpenMetaverse prim["description"] = LLSD.FromString(Properties.Description); prim["phantom"] = LLSD.FromBoolean(((Flags & ObjectFlags.Phantom) != 0)); prim["physical"] = LLSD.FromBoolean(((Flags & ObjectFlags.Physics) != 0)); - prim["position"] = Position.GetLLSD(); - prim["rotation"] = Rotation.GetLLSD(); - prim["scale"] = Scale.GetLLSD(); + prim["position"] = LLSD.FromVector3(Position); + prim["rotation"] = LLSD.FromQuaternion(Rotation); + prim["scale"] = LLSD.FromVector3(Scale); prim["material"] = LLSD.FromInteger((int)Data.Material); prim["shadows"] = LLSD.FromBoolean(((Flags & ObjectFlags.CastShadows) != 0)); prim["textures"] = Textures.GetLLSD(); @@ -635,9 +635,9 @@ namespace OpenMetaverse prim.Flags |= ObjectFlags.CastShadows; prim.ParentID = (uint)map["parentid"].AsInteger(); - prim.Position.FromLLSD(map["position"]); - prim.Rotation.FromLLSD(map["rotation"]); - prim.Scale.FromLLSD(map["scale"]); + prim.Position = ((LLSDArray)map["position"]).AsVector3(); + prim.Rotation = ((LLSDArray)map["rotation"]).AsQuaternion(); + prim.Scale = ((LLSDArray)map["scale"]).AsVector3(); prim.Data.Material = (MaterialType)map["material"].AsInteger(); prim.Flexible = FlexibleData.FromLLSD(map["flex"]); prim.Light = LightData.FromLLSD(map["light"]); diff --git a/OpenMetaverse/Simulator.cs b/OpenMetaverse/Simulator.cs index 693b177f..d254f0eb 100644 --- a/OpenMetaverse/Simulator.cs +++ b/OpenMetaverse/Simulator.cs @@ -844,7 +844,7 @@ namespace OpenMetaverse catch (MalformedDataException) { Logger.Log(String.Format("Malformed data, cannot parse packet:\n{0}", - Helpers.FieldToHexString(buffer.Data, buffer.DataLength, null)), Helpers.LogLevel.Error); + Utils.BytesToHexString(buffer.Data, buffer.DataLength, null)), Helpers.LogLevel.Error); } // Fail-safe check diff --git a/OpenMetaverse/TextureEntry.cs b/OpenMetaverse/TextureEntry.cs index 3f8f7bf4..315393a7 100644 --- a/OpenMetaverse/TextureEntry.cs +++ b/OpenMetaverse/TextureEntry.cs @@ -436,7 +436,7 @@ namespace OpenMetaverse { LLSDMap tex = new LLSDMap(10); if (faceNumber >= 0) tex["face_number"] = LLSD.FromInteger(faceNumber); - tex["colors"] = RGBA.GetLLSD(); + tex["colors"] = LLSD.FromColor4(RGBA); tex["scales"] = LLSD.FromReal(RepeatU); tex["scalet"] = LLSD.FromReal(RepeatV); tex["offsets"] = LLSD.FromReal(OffsetU); @@ -464,7 +464,7 @@ namespace OpenMetaverse TextureEntryFace face = new TextureEntryFace(defaultFace); faceNumber = (map.ContainsKey("face_number")) ? map["face_number"].AsInteger() : -1; Color4 rgba = face.RGBA; - rgba.FromLLSD(map["colors"]); + rgba = ((LLSDArray)map["colors"]).AsColor4(); face.RGBA = rgba; face.RepeatU = (float)map["scales"].AsReal(); face.RepeatV = (float)map["scalet"].AsReal(); diff --git a/OpenMetaverse/Types/Color4.cs b/OpenMetaverse/Types/Color4.cs index 8d4ef432..ce4b97ce 100644 --- a/OpenMetaverse/Types/Color4.cs +++ b/OpenMetaverse/Types/Color4.cs @@ -26,7 +26,6 @@ using System; using System.Runtime.InteropServices; -using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -70,15 +69,15 @@ namespace OpenMetaverse // Quick check to see if someone is doing something obviously wrong // like using float values from 0.0 - 255.0 if (r > 1f || g > 1f || b > 1f || a > 1f) - Logger.Log( + throw new ArgumentException( String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>", - r, g, b, a), Helpers.LogLevel.Warning); + r, g, b, a)); // Valid range is from 0.0 to 1.0 - R = MathHelper.Clamp(r, 0f, 1f); - G = MathHelper.Clamp(g, 0f, 1f); - B = MathHelper.Clamp(b, 0f, 1f); - A = MathHelper.Clamp(a, 0f, 1f); + R = Utils.Clamp(r, 0f, 1f); + G = Utils.Clamp(g, 0f, 1f); + B = Utils.Clamp(b, 0f, 1f); + A = Utils.Clamp(a, 0f, 1f); } /// @@ -219,10 +218,10 @@ namespace OpenMetaverse { byte[] byteArray = new byte[4]; - byteArray[0] = Helpers.FloatToByte(R, 0f, 1f); - byteArray[1] = Helpers.FloatToByte(G, 0f, 1f); - byteArray[2] = Helpers.FloatToByte(B, 0f, 1f); - byteArray[3] = Helpers.FloatToByte(A, 0f, 1f); + byteArray[0] = Utils.FloatToByte(R, 0f, 1f); + byteArray[1] = Utils.FloatToByte(G, 0f, 1f); + byteArray[2] = Utils.FloatToByte(B, 0f, 1f); + byteArray[3] = Utils.FloatToByte(A, 0f, 1f); if (inverted) { @@ -280,36 +279,6 @@ namespace OpenMetaverse } } - public LLSD GetLLSD() - { - LLSDArray array = new LLSDArray(); - array.Add(LLSD.FromReal(R)); - array.Add(LLSD.FromReal(G)); - array.Add(LLSD.FromReal(B)); - array.Add(LLSD.FromReal(A)); - return array; - } - - public void FromLLSD(LLSD llsd) - { - if (llsd.Type == LLSDType.Array) - { - LLSDArray array = (LLSDArray)llsd; - - if (array.Count == 4) - { - R = (float)array[0].AsReal(); - G = (float)array[1].AsReal(); - B = (float)array[2].AsReal(); - A = (float)array[3].AsReal(); - - return; - } - } - - this = Color4.Black; - } - #endregion Public Methods #region Static Methods @@ -320,12 +289,12 @@ namespace OpenMetaverse public override string ToString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); + return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); } public string ToRGBString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); + return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); } public override bool Equals(object obj) diff --git a/OpenMetaverse/Types/Matrix4.cs b/OpenMetaverse/Types/Matrix4.cs index a65a0352..375ae92a 100644 --- a/OpenMetaverse/Types/Matrix4.cs +++ b/OpenMetaverse/Types/Matrix4.cs @@ -173,7 +173,7 @@ namespace OpenMetaverse double cx, cy, cz; // cosines double sx, sz; // sines - angleY = Math.Asin(MathHelper.Clamp(M13, -1f, 1f)); + angleY = Math.Asin(Utils.Clamp(M13, -1f, 1f)); cy = Math.Cos(angleY); if (Math.Abs(cy) > 0.005f) @@ -899,7 +899,7 @@ namespace OpenMetaverse /// A string representation of the vector public override string ToString() { - return string.Format(Helpers.EnUsCulture, + return string.Format(Utils.EnUsCulture, "|{0}, {1}, {2}, {3}|\n|{4}, {5}, {6}, {7}|\n|{8}, {9}, {10}, {11}|\n|{12}, {13}, {14}, {15}|", M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44); } diff --git a/OpenMetaverse/Types/Quaternion.cs b/OpenMetaverse/Types/Quaternion.cs index 57e26b1b..a6808de4 100644 --- a/OpenMetaverse/Types/Quaternion.cs +++ b/OpenMetaverse/Types/Quaternion.cs @@ -27,7 +27,6 @@ using System; using System.Runtime.InteropServices; using System.Globalization; -using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -246,36 +245,6 @@ namespace OpenMetaverse return bytes; } - public LLSD GetLLSD() - { - LLSDArray array = new LLSDArray(); - array.Add(LLSD.FromReal(X)); - array.Add(LLSD.FromReal(Y)); - array.Add(LLSD.FromReal(Z)); - array.Add(LLSD.FromReal(W)); - return array; - } - - public void FromLLSD(LLSD llsd) - { - if (llsd.Type == LLSDType.Array) - { - LLSDArray array = (LLSDArray)llsd; - - if (array.Count == 4) - { - X = (float)array[0].AsReal(); - Y = (float)array[1].AsReal(); - Z = (float)array[2].AsReal(); - W = (float)array[3].AsReal(); - - return; - } - } - - this = Quaternion.Identity; - } - /// /// Convert this quaternion to euler angles /// @@ -422,7 +391,7 @@ namespace OpenMetaverse /// Quaternion representation of the euler angles public static Quaternion CreateFromEulers(float roll, float pitch, float yaw) { - if (roll > Helpers.TWO_PI || pitch > Helpers.TWO_PI || yaw > Helpers.TWO_PI) + if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI) throw new ArgumentException("Euler angles must be in radians"); double atCos = Math.Cos(roll / 2f); @@ -582,8 +551,8 @@ namespace OpenMetaverse q2.Z = -q1.W; q2.W = q1.Z; - scale = (float)Math.Sin(MathHelper.PI * (0.5f - amount)); - invscale = (float)Math.Sin(MathHelper.PI * amount); + scale = (float)Math.Sin(Utils.PI * (0.5f - amount)); + invscale = (float)Math.Sin(Utils.PI * amount); } return (q1 * scale) + (q2 * invscale); @@ -658,17 +627,17 @@ namespace OpenMetaverse if (split.Length == 3) { return new Quaternion( - float.Parse(split[0].Trim(), Helpers.EnUsCulture), - float.Parse(split[1].Trim(), Helpers.EnUsCulture), - float.Parse(split[2].Trim(), Helpers.EnUsCulture)); + float.Parse(split[0].Trim(), Utils.EnUsCulture), + float.Parse(split[1].Trim(), Utils.EnUsCulture), + float.Parse(split[2].Trim(), Utils.EnUsCulture)); } else { return new Quaternion( - float.Parse(split[0].Trim(), Helpers.EnUsCulture), - float.Parse(split[1].Trim(), Helpers.EnUsCulture), - float.Parse(split[2].Trim(), Helpers.EnUsCulture), - float.Parse(split[3].Trim(), Helpers.EnUsCulture)); + float.Parse(split[0].Trim(), Utils.EnUsCulture), + float.Parse(split[1].Trim(), Utils.EnUsCulture), + float.Parse(split[2].Trim(), Utils.EnUsCulture), + float.Parse(split[3].Trim(), Utils.EnUsCulture)); } } @@ -710,7 +679,7 @@ namespace OpenMetaverse public override string ToString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); + return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); } /// diff --git a/OpenMetaverse/Types/UUID.cs b/OpenMetaverse/Types/UUID.cs index 14a005ec..90b0c95b 100644 --- a/OpenMetaverse/Types/UUID.cs +++ b/OpenMetaverse/Types/UUID.cs @@ -165,7 +165,17 @@ namespace OpenMetaverse /// An integer created from the first eight bytes of this UUID public ulong GetULong() { - return Helpers.BytesToUInt64(Guid.ToByteArray()); + byte[] bytes = Guid.ToByteArray(); + + return (ulong) + ((ulong)bytes[7] + + ((ulong)bytes[6] << 8) + + ((ulong)bytes[5] << 16) + + ((ulong)bytes[4] << 24) + + ((ulong)bytes[3] << 32) + + ((ulong)bytes[2] << 40) + + ((ulong)bytes[1] << 48) + + ((ulong)bytes[0] << 56)); } #endregion Public Methods @@ -220,7 +230,7 @@ namespace OpenMetaverse Buffer.BlockCopy(first.GetBytes(), 0, input, 0, 16); Buffer.BlockCopy(second.GetBytes(), 0, input, 16, 16); - return new UUID(Helpers.MD5Builder.ComputeHash(input), 0); + return new UUID(Utils.MD5Builder.ComputeHash(input), 0); } /// diff --git a/OpenMetaverse/Types/Utils.cs b/OpenMetaverse/Types/Utils.cs new file mode 100644 index 00000000..9850eeee --- /dev/null +++ b/OpenMetaverse/Types/Utils.cs @@ -0,0 +1,590 @@ +/* + * Copyright (c) 2008, openmetaverse.org + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.org nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Text; + +namespace OpenMetaverse +{ + public static class Utils + { + /// + /// Operating system + /// + public enum Platform + { + /// Unknown + Unknown, + /// Microsoft Windows + Windows, + /// Microsoft Windows CE + WindowsCE, + /// Linux + Linux, + /// Apple OSX + OSX + } + + /// + /// Runtime platform + /// + public enum Runtime + { + /// .NET runtime + Windows, + /// Mono runtime: http://www.mono-project.com/ + Mono + } + + public const float E = (float)Math.E; + public const float LOG10E = 0.4342945f; + public const float LOG2E = 1.442695f; + public const float PI = (float)Math.PI; + public const float TWO_PI = (float)(Math.PI * 2.0d); + public const float PI_OVER_TWO = (float)(Math.PI / 2.0d); + public const float PI_OVER_FOUR = (float)(Math.PI / 4.0d); + /// Used for converting degrees to radians + public const float DEG_TO_RAD = (float)(Math.PI / 180.0d); + /// Used for converting radians to degrees + public const float RAD_TO_DEG = (float)(180.0d / Math.PI); + + /// Provide a single instance of the CultureInfo class to + /// help parsing in situations where the grid assumes an en-us + /// culture + public static readonly System.Globalization.CultureInfo EnUsCulture = + new System.Globalization.CultureInfo("en-us"); + + /// Provide a single instance of the MD5 class to avoid making + /// duplicate copies + public static readonly System.Security.Cryptography.MD5 MD5Builder = + new System.Security.Cryptography.MD5CryptoServiceProvider(); + + /// UNIX epoch in DateTime format + public static readonly DateTime Epoch = new DateTime(1970, 1, 1); + + #region Math + + /// + /// Clamp a given value between a range + /// + /// Value to clamp + /// Minimum allowable value + /// Maximum allowable value + /// A value inclusively between lower and upper + public static float Clamp(float value, float min, float max) + { + // First we check to see if we're greater than the max + value = (value > max) ? max : value; + + // Then we check to see if we're less than the min. + value = (value < min) ? min : value; + + // There's no check to see if min > max. + return value; + } + + /// + /// Clamp a given value between a range + /// + /// Value to clamp + /// Minimum allowable value + /// Maximum allowable value + /// A value inclusively between lower and upper + public static double Clamp(double value, double min, double max) + { + // First we check to see if we're greater than the max + value = (value > max) ? max : value; + + // Then we check to see if we're less than the min. + value = (value < min) ? min : value; + + // There's no check to see if min > max. + return value; + } + + /// + /// Round a floating-point value to the nearest integer + /// + /// Floating point number to round + /// Integer + public static int Round(float val) + { + return (int)Math.Floor(val + 0.5f); + } + + /// + /// Test if a single precision float is a finite number + /// + public static bool IsFinite(float value) + { + return !(Single.IsNaN(value) || Single.IsInfinity(value)); + } + + /// + /// Test if a double precision float is a finite number + /// + public static bool IsFinite(double value) + { + return !(Double.IsNaN(value) || Double.IsInfinity(value)); + } + + /// + /// Get the distance between two floating-point values + /// + /// First value + /// Second value + /// The distance between the two values + public static float Distance(float value1, float value2) + { + return Math.Abs(value1 - value2); + } + + public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) + { + // All transformed to double not to lose precission + // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity + double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; + double sCubed = s * s * s; + double sSquared = s * s; + + if (amount == 0f) + result = value1; + else if (amount == 1f) + result = value2; + else + result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + + t1 * s + v1; + return (float)result; + } + + public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount) + { + // All transformed to double not to lose precission + // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity + double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; + double sCubed = s * s * s; + double sSquared = s * s; + + if (amount == 0d) + result = value1; + else if (amount == 1f) + result = value2; + else + result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + + t1 * s + v1; + return result; + } + + public static float Lerp(float value1, float value2, float amount) + { + return value1 + (value2 - value1) * amount; + } + + public static double Lerp(double value1, double value2, double amount) + { + return value1 + (value2 - value1) * amount; + } + + public static float SmoothStep(float value1, float value2, float amount) + { + // It is expected that 0 < amount < 1 + // If amount < 0, return value1 + // If amount > 1, return value2 + float result = Utils.Clamp(amount, 0f, 1f); + return Utils.Hermite(value1, 0f, value2, 0f, result); + } + + public static double SmoothStep(double value1, double value2, double amount) + { + // It is expected that 0 < amount < 1 + // If amount < 0, return value1 + // If amount > 1, return value2 + double result = Utils.Clamp(amount, 0f, 1f); + return Utils.Hermite(value1, 0f, value2, 0f, result); + } + + public static float ToDegrees(float radians) + { + // This method uses double precission internally, + // though it returns single float + // Factor = 180 / pi + return (float)(radians * 57.295779513082320876798154814105); + } + + public static float ToRadians(float degrees) + { + // This method uses double precission internally, + // though it returns single float + // Factor = pi / 180 + return (float)(degrees * 0.017453292519943295769236907684886); + } + + /// + /// Calculate the MD5 hash of a given string + /// + /// The password to hash + /// An MD5 hash in string format, with $1$ prepended + public static string MD5(string password) + { + StringBuilder digest = new StringBuilder(); + byte[] hash; + lock (MD5Builder) hash = MD5Builder.ComputeHash(ASCIIEncoding.Default.GetBytes(password)); + + // Convert the hash to a hex string + foreach (byte b in hash) + { + digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); + } + + return "$1$" + digest.ToString(); + } + + #endregion Math + + #region Platform + + /// + /// Get the current running platform + /// + /// Enumeration of the current platform we are running on + public static Platform GetRunningPlatform() + { + const string OSX_CHECK_FILE = "/Library/Extensions.kextcache"; + + if (Environment.OSVersion.Platform == PlatformID.WinCE) + { + return Platform.WindowsCE; + } + else + { + int plat = (int)Environment.OSVersion.Platform; + + if ((plat != 4) && (plat != 128)) + { + return Platform.Windows; + } + else + { + if (System.IO.File.Exists(OSX_CHECK_FILE)) + return Platform.OSX; + else + return Platform.Linux; + } + } + } + + /// + /// Get the current running runtime + /// + /// Enumeration of the current runtime we are running on + public static Runtime GetRunningRuntime() + { + Type t = Type.GetType("Mono.Runtime"); + if (t != null) + return Runtime.Mono; + else + return Runtime.Windows; + } + + #endregion Platform + + #region Conversion + + /// + /// Convert four bytes in little endian ordering to a floating point + /// value + /// + /// Byte array containing a little ending floating + /// point value + /// Starting position of the floating point value in + /// the byte array + /// Single precision value + public static float BytesToFloat(byte[] bytes, int pos) + { + if (!BitConverter.IsLittleEndian) Array.Reverse(bytes, pos, 4); + return BitConverter.ToSingle(bytes, pos); + } + + /// + /// Convert a float value to a byte given a minimum and maximum range + /// + /// Value to convert to a byte + /// Minimum value range + /// Maximum value range + /// A single byte representing the original float value + public static byte FloatToByte(float val, float lower, float upper) + { + val = Clamp(val, lower, upper); + // Normalize the value + val -= lower; + val /= (upper - lower); + + return (byte)Math.Floor(val * (float)byte.MaxValue); + } + + /// + /// Convert a floating point value to four bytes in little endian + /// ordering + /// + /// A floating point value + /// A four byte array containing the value in little endian + /// ordering + public static byte[] FloatToBytes(float value) + { + byte[] bytes = BitConverter.GetBytes(value); + if (!BitConverter.IsLittleEndian) + Array.Reverse(bytes); + return bytes; + } + + /// + /// Convert an IP address object to an unsigned 32-bit integer + /// + /// IP address to convert + /// 32-bit unsigned integer holding the IP address bits + public static uint IPToUInt(System.Net.IPAddress address) + { + byte[] bytes = address.GetAddressBytes(); + return (uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]); + } + + /// + /// Convert a variable length UTF8 byte array to a string + /// + /// The UTF8 encoded byte array to convert + /// The decoded string + public static string BytesToString(byte[] bytes) + { + if (bytes.Length > 0 && bytes[bytes.Length - 1] == 0x00) + return UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1); + else + return UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length); + } + + /// + /// Converts a byte array to a string containing hexadecimal characters + /// + /// The byte array to convert to a string + /// The name of the field to prepend to each + /// line of the string + /// A string containing hexadecimal characters on multiple + /// lines. Each line is prepended with the field name + public static string BytesToHexString(byte[] bytes, string fieldName) + { + return BytesToHexString(bytes, bytes.Length, fieldName); + } + + /// + /// Converts a byte array to a string containing hexadecimal characters + /// + /// The byte array to convert to a string + /// Number of bytes in the array to parse + /// A string to prepend to each line of the hex + /// dump + /// A string containing hexadecimal characters on multiple + /// lines. Each line is prepended with the field name + public static string BytesToHexString(byte[] bytes, int length, string fieldName) + { + StringBuilder output = new StringBuilder(); + + for (int i = 0; i < length; i += 16) + { + if (i != 0) + output.Append('\n'); + + if (!String.IsNullOrEmpty(fieldName)) + { + output.Append(fieldName); + output.Append(": "); + } + + for (int j = 0; j < 16; j++) + { + if ((i + j) < length) + output.Append(String.Format("{0:X2} ", bytes[i + j])); + else + output.Append(" "); + } + } + + return output.ToString(); + } + + /// + /// Convert a string to a UTF8 encoded byte array + /// + /// The string to convert + /// A null-terminated UTF8 byte array + public static byte[] StringToBytes(string str) + { + if (str.Length == 0) { return new byte[0]; } + if (!str.EndsWith("\0")) { str += "\0"; } + return System.Text.UTF8Encoding.UTF8.GetBytes(str); + } + + ///// + ///// Converts a string containing hexadecimal characters to a byte array + ///// + ///// String containing hexadecimal characters + ///// The converted byte array + //public static byte[] HexStringToBytes(string hexString) + //{ + // string newString = ""; + // char c; + + // // FIXME: For each line of the string, if a colon is found + // // remove everything before it + + // // remove all non A-F, 0-9, characters + // for (int i = 0; i < hexString.Length; i++) + // { + // c = hexString[i]; + // if (IsHexDigit(c)) + // newString += c; + // } + + // // if odd number of characters, discard last character + // if (newString.Length % 2 != 0) + // { + // newString = newString.Substring(0, newString.Length - 1); + // } + + // int byteLength = newString.Length / 2; + // byte[] bytes = new byte[byteLength]; + // string hex; + // int j = 0; + // for (int i = 0; i < bytes.Length; i++) + // { + // hex = new String(new Char[] { newString[j], newString[j + 1] }); + // bytes[i] = HexToByte(hex); + // j = j + 2; + // } + // return bytes; + //} + + /// + /// Gets a unix timestamp for the current time + /// + /// An unsigned integer representing a unix timestamp for now + public static uint GetUnixTime() + { + return (uint)(DateTime.UtcNow - Epoch).TotalSeconds; + } + + /// + /// Convert a UNIX timestamp to a native DateTime object + /// + /// An unsigned integer representing a UNIX + /// timestamp + /// A DateTime object containing the same time specified in + /// the given timestamp + public static DateTime UnixTimeToDateTime(uint timestamp) + { + System.DateTime dateTime = Epoch; + + // Add the number of seconds in our UNIX timestamp + dateTime = dateTime.AddSeconds(timestamp); + + return dateTime; + } + + /// + /// Convert a UNIX timestamp to a native DateTime object + /// + /// A signed integer representing a UNIX + /// timestamp + /// A DateTime object containing the same time specified in + /// the given timestamp + public static DateTime UnixTimeToDateTime(int timestamp) + { + return DateTime.FromBinary(timestamp); + } + + /// + /// Convert a native DateTime object to a UNIX timestamp + /// + /// A DateTime object you want to convert to a + /// timestamp + /// An unsigned integer representing a UNIX timestamp + public static uint DateTimeToUnixTime(DateTime time) + { + TimeSpan ts = (time - new DateTime(1970, 1, 1, 0, 0, 0)); + return (uint)ts.TotalSeconds; + } + + /// + /// Swap two values + /// + /// Type of the values to swap + /// First value + /// Second value + public static void Swap(ref T lhs, ref T rhs) + { + T temp = lhs; + lhs = rhs; + rhs = temp; + } + + /// + /// Attempts to parse a floating point value from a string, using an + /// EN-US number format + /// + /// String to parse + /// Resulting floating point number + /// True if the parse was successful, otherwise false + public static bool TryParseSingle(string s, out float result) + { + return Single.TryParse(s, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat, out result); + } + + /// + /// Attempts to parse a floating point value from a string, using an + /// EN-US number format + /// + /// String to parse + /// Resulting floating point number + /// True if the parse was successful, otherwise false + public static bool TryParseDouble(string s, out double result) + { + return Double.TryParse(s, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat, out result); + } + + /// + /// Tries to parse an unsigned 32-bit integer from a hexadecimal string + /// + /// String to parse + /// Resulting integer + /// True if the parse was successful, otherwise false + public static bool TryParseHex(string s, out uint result) + { + return UInt32.TryParse(s, System.Globalization.NumberStyles.HexNumber, EnUsCulture.NumberFormat, out result); + } + + #endregion Conversion + } +} diff --git a/OpenMetaverse/Types/Vector2.cs b/OpenMetaverse/Types/Vector2.cs index 76e9152e..b7d46be6 100644 --- a/OpenMetaverse/Types/Vector2.cs +++ b/OpenMetaverse/Types/Vector2.cs @@ -27,7 +27,6 @@ using System; using System.Runtime.InteropServices; using System.Globalization; -using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -93,7 +92,7 @@ namespace OpenMetaverse /// public bool IsFinite() { - return MathHelper.IsFinite(X) && MathHelper.IsFinite(Y); + return Utils.IsFinite(X) && Utils.IsFinite(Y); } /// @@ -168,32 +167,6 @@ namespace OpenMetaverse this = Normalize(this); } - public LLSD GetLLSD() - { - LLSDArray array = new LLSDArray(); - array.Add(LLSD.FromReal(X)); - array.Add(LLSD.FromReal(Y)); - return array; - } - - public void FromLLSD(LLSD llsd) - { - if (llsd.Type == LLSDType.Array) - { - LLSDArray array = (LLSDArray)llsd; - - if (array.Count == 2) - { - X = (float)array[0].AsReal(); - Y = (float)array[1].AsReal(); - - return; - } - } - - this = Vector2.Zero; - } - #endregion Public Methods #region Static Methods @@ -208,8 +181,8 @@ namespace OpenMetaverse public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { return new Vector2( - MathHelper.Clamp(value1.X, min.X, max.X), - MathHelper.Clamp(value1.Y, min.Y, max.Y)); + Utils.Clamp(value1.X, min.X, max.X), + Utils.Clamp(value1.Y, min.Y, max.Y)); } public static float Distance(Vector2 value1, Vector2 value2) @@ -245,8 +218,8 @@ namespace OpenMetaverse public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2( - MathHelper.Lerp(value1.X, value2.X, amount), - MathHelper.Lerp(value1.Y, value2.Y, amount)); + Utils.Lerp(value1.X, value2.X, amount), + Utils.Lerp(value1.Y, value2.Y, amount)); } public static Vector2 Max(Vector2 value1, Vector2 value2) @@ -312,9 +285,9 @@ namespace OpenMetaverse char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector3( - float.Parse(split[0].Trim(), Helpers.EnUsCulture), - float.Parse(split[1].Trim(), Helpers.EnUsCulture), - float.Parse(split[2].Trim(), Helpers.EnUsCulture)); + float.Parse(split[0].Trim(), Utils.EnUsCulture), + float.Parse(split[1].Trim(), Utils.EnUsCulture), + float.Parse(split[2].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector3 result) @@ -337,8 +310,8 @@ namespace OpenMetaverse public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount) { return new Vector2( - MathHelper.SmoothStep(value1.X, value2.X, amount), - MathHelper.SmoothStep(value1.Y, value2.Y, amount)); + Utils.SmoothStep(value1.X, value2.X, amount), + Utils.SmoothStep(value1.Y, value2.Y, amount)); } public static Vector2 Subtract(Vector2 value1, Vector2 value2) @@ -387,7 +360,7 @@ namespace OpenMetaverse /// A string representation of the vector public override string ToString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}>", X, Y); + return String.Format(Utils.EnUsCulture, "<{0}, {1}>", X, Y); } /// diff --git a/OpenMetaverse/Types/Vector3.cs b/OpenMetaverse/Types/Vector3.cs index cadb488e..cfbe10ad 100644 --- a/OpenMetaverse/Types/Vector3.cs +++ b/OpenMetaverse/Types/Vector3.cs @@ -27,7 +27,6 @@ using System; using System.Runtime.InteropServices; using System.Globalization; -using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -149,7 +148,7 @@ namespace OpenMetaverse /// public bool IsFinite() { - return (MathHelper.IsFinite(X) && MathHelper.IsFinite(Y) && MathHelper.IsFinite(Z)); + return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); } /// @@ -206,34 +205,6 @@ namespace OpenMetaverse return byteArray; } - public LLSD GetLLSD() - { - LLSDArray array = new LLSDArray(); - array.Add(LLSD.FromReal(X)); - array.Add(LLSD.FromReal(Y)); - array.Add(LLSD.FromReal(Z)); - return array; - } - - public void FromLLSD(LLSD llsd) - { - if (llsd.Type == LLSDType.Array) - { - LLSDArray array = (LLSDArray)llsd; - - if (array.Count == 3) - { - X = (float)array[0].AsReal(); - Y = (float)array[1].AsReal(); - Z = (float)array[2].AsReal(); - - return; - } - } - - this = Vector3.Zero; - } - #endregion Public Methods #region Static Methods @@ -249,9 +220,9 @@ namespace OpenMetaverse public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { return new Vector3( - MathHelper.Clamp(value1.X, min.X, max.X), - MathHelper.Clamp(value1.Y, min.Y, max.Y), - MathHelper.Clamp(value1.Z, min.Z, max.Z)); + Utils.Clamp(value1.X, min.X, max.X), + Utils.Clamp(value1.Y, min.Y, max.Y), + Utils.Clamp(value1.Z, min.Z, max.Z)); } public static Vector3 Cross(Vector3 value1, Vector3 value2) @@ -300,9 +271,9 @@ namespace OpenMetaverse public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { return new Vector3( - MathHelper.Lerp(value1.X, value2.X, amount), - MathHelper.Lerp(value1.Y, value2.Y, amount), - MathHelper.Lerp(value1.Z, value2.Z, amount)); + Utils.Lerp(value1.X, value2.X, amount), + Utils.Lerp(value1.Y, value2.Y, amount), + Utils.Lerp(value1.Z, value2.Z, amount)); } public static Vector3 Max(Vector3 value1, Vector3 value2) @@ -375,9 +346,9 @@ namespace OpenMetaverse char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector3( - Single.Parse(split[0].Trim(), Helpers.EnUsCulture), - Single.Parse(split[1].Trim(), Helpers.EnUsCulture), - Single.Parse(split[2].Trim(), Helpers.EnUsCulture)); + Single.Parse(split[0].Trim(), Utils.EnUsCulture), + Single.Parse(split[1].Trim(), Utils.EnUsCulture), + Single.Parse(split[2].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector3 result) @@ -421,9 +392,9 @@ namespace OpenMetaverse public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount) { return new Vector3( - MathHelper.SmoothStep(value1.X, value2.X, amount), - MathHelper.SmoothStep(value1.Y, value2.Y, amount), - MathHelper.SmoothStep(value1.Z, value2.Z, amount)); + Utils.SmoothStep(value1.X, value2.X, amount), + Utils.SmoothStep(value1.Y, value2.Y, amount), + Utils.SmoothStep(value1.Z, value2.Z, amount)); } public static Vector3 Subtract(Vector3 value1, Vector3 value2) @@ -475,7 +446,7 @@ namespace OpenMetaverse /// A string representation of the vector public override string ToString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); + return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); } /// diff --git a/OpenMetaverse/Types/Vector3d.cs b/OpenMetaverse/Types/Vector3d.cs index 0b205227..085d8d48 100644 --- a/OpenMetaverse/Types/Vector3d.cs +++ b/OpenMetaverse/Types/Vector3d.cs @@ -27,7 +27,6 @@ using System; using System.Runtime.InteropServices; using System.Globalization; -using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -141,7 +140,7 @@ namespace OpenMetaverse /// public bool IsFinite() { - return (MathHelper.IsFinite(X) && MathHelper.IsFinite(Y) && MathHelper.IsFinite(Z)); + return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); } /// @@ -198,34 +197,6 @@ namespace OpenMetaverse return byteArray; } - public LLSD GetLLSD() - { - LLSDArray array = new LLSDArray(); - array.Add(LLSD.FromReal(X)); - array.Add(LLSD.FromReal(Y)); - array.Add(LLSD.FromReal(Z)); - return array; - } - - public void FromLLSD(LLSD llsd) - { - if (llsd.Type == LLSDType.Array) - { - LLSDArray array = (LLSDArray)llsd; - - if (array.Count == 3) - { - X = array[0].AsReal(); - Y = array[1].AsReal(); - Z = array[2].AsReal(); - - return; - } - } - - this = Vector3d.Zero; - } - #endregion Public Methods #region Static Methods @@ -241,9 +212,9 @@ namespace OpenMetaverse public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max) { return new Vector3d( - MathHelper.Clamp(value1.X, min.X, max.X), - MathHelper.Clamp(value1.Y, min.Y, max.Y), - MathHelper.Clamp(value1.Z, min.Z, max.Z)); + Utils.Clamp(value1.X, min.X, max.X), + Utils.Clamp(value1.Y, min.Y, max.Y), + Utils.Clamp(value1.Z, min.Z, max.Z)); } public static Vector3d Cross(Vector3d value1, Vector3d value2) @@ -292,9 +263,9 @@ namespace OpenMetaverse public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount) { return new Vector3d( - MathHelper.Lerp(value1.X, value2.X, amount), - MathHelper.Lerp(value1.Y, value2.Y, amount), - MathHelper.Lerp(value1.Z, value2.Z, amount)); + Utils.Lerp(value1.X, value2.X, amount), + Utils.Lerp(value1.Y, value2.Y, amount), + Utils.Lerp(value1.Z, value2.Z, amount)); } public static Vector3d Max(Vector3d value1, Vector3d value2) @@ -366,9 +337,9 @@ namespace OpenMetaverse char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector3d( - Double.Parse(split[0].Trim(), Helpers.EnUsCulture), - Double.Parse(split[1].Trim(), Helpers.EnUsCulture), - Double.Parse(split[2].Trim(), Helpers.EnUsCulture)); + Double.Parse(split[0].Trim(), Utils.EnUsCulture), + Double.Parse(split[1].Trim(), Utils.EnUsCulture), + Double.Parse(split[2].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector3d result) @@ -391,9 +362,9 @@ namespace OpenMetaverse public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount) { return new Vector3d( - MathHelper.SmoothStep(value1.X, value2.X, amount), - MathHelper.SmoothStep(value1.Y, value2.Y, amount), - MathHelper.SmoothStep(value1.Z, value2.Z, amount)); + Utils.SmoothStep(value1.X, value2.X, amount), + Utils.SmoothStep(value1.Y, value2.Y, amount), + Utils.SmoothStep(value1.Z, value2.Z, amount)); } public static Vector3d Subtract(Vector3d value1, Vector3d value2) @@ -429,7 +400,7 @@ namespace OpenMetaverse /// A string representation of the vector public override string ToString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); + return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); } /// diff --git a/OpenMetaverse/Types/Vector4.cs b/OpenMetaverse/Types/Vector4.cs index dc41179c..8173e2dd 100644 --- a/OpenMetaverse/Types/Vector4.cs +++ b/OpenMetaverse/Types/Vector4.cs @@ -27,7 +27,6 @@ using System; using System.Runtime.InteropServices; using System.Globalization; -using OpenMetaverse.StructuredData; namespace OpenMetaverse { @@ -153,7 +152,7 @@ namespace OpenMetaverse /// public bool IsFinite() { - return (MathHelper.IsFinite(X) && MathHelper.IsFinite(Y) && MathHelper.IsFinite(Z) && MathHelper.IsFinite(W)); + return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z) && Utils.IsFinite(W)); } /// @@ -215,36 +214,6 @@ namespace OpenMetaverse return byteArray; } - public LLSD GetLLSD() - { - LLSDArray array = new LLSDArray(); - array.Add(LLSD.FromReal(X)); - array.Add(LLSD.FromReal(Y)); - array.Add(LLSD.FromReal(Z)); - array.Add(LLSD.FromReal(W)); - return array; - } - - public void FromLLSD(LLSD llsd) - { - if (llsd.Type == LLSDType.Array) - { - LLSDArray array = (LLSDArray)llsd; - - if (array.Count == 4) - { - X = (float)array[0].AsReal(); - Y = (float)array[1].AsReal(); - Z = (float)array[2].AsReal(); - W = (float)array[3].AsReal(); - - return; - } - } - - this = Vector4.Zero; - } - #endregion Public Methods #region Static Methods @@ -261,10 +230,10 @@ namespace OpenMetaverse public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { return new Vector4( - MathHelper.Clamp(value1.X, min.X, max.X), - MathHelper.Clamp(value1.Y, min.Y, max.Y), - MathHelper.Clamp(value1.Z, min.Z, max.Z), - MathHelper.Clamp(value1.W, min.W, max.W)); + Utils.Clamp(value1.X, min.X, max.X), + Utils.Clamp(value1.Y, min.Y, max.Y), + Utils.Clamp(value1.Z, min.Z, max.Z), + Utils.Clamp(value1.W, min.W, max.W)); } public static float Distance(Vector4 value1, Vector4 value2) @@ -308,10 +277,10 @@ namespace OpenMetaverse public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount) { return new Vector4( - MathHelper.Lerp(value1.X, value2.X, amount), - MathHelper.Lerp(value1.Y, value2.Y, amount), - MathHelper.Lerp(value1.Z, value2.Z, amount), - MathHelper.Lerp(value1.W, value2.W, amount)); + Utils.Lerp(value1.X, value2.X, amount), + Utils.Lerp(value1.Y, value2.Y, amount), + Utils.Lerp(value1.Z, value2.Z, amount), + Utils.Lerp(value1.W, value2.W, amount)); } public static Vector4 Max(Vector4 value1, Vector4 value2) @@ -384,10 +353,10 @@ namespace OpenMetaverse public static Vector4 SmoothStep(Vector4 value1, Vector4 value2, float amount) { return new Vector4( - MathHelper.SmoothStep(value1.X, value2.X, amount), - MathHelper.SmoothStep(value1.Y, value2.Y, amount), - MathHelper.SmoothStep(value1.Z, value2.Z, amount), - MathHelper.SmoothStep(value1.W, value2.W, amount)); + Utils.SmoothStep(value1.X, value2.X, amount), + Utils.SmoothStep(value1.Y, value2.Y, amount), + Utils.SmoothStep(value1.Z, value2.Z, amount), + Utils.SmoothStep(value1.W, value2.W, amount)); } public static Vector4 Subtract(Vector4 value1, Vector4 value2) @@ -431,10 +400,10 @@ namespace OpenMetaverse char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector4( - float.Parse(split[0].Trim(), Helpers.EnUsCulture), - float.Parse(split[1].Trim(), Helpers.EnUsCulture), - float.Parse(split[2].Trim(), Helpers.EnUsCulture), - float.Parse(split[3].Trim(), Helpers.EnUsCulture)); + float.Parse(split[0].Trim(), Utils.EnUsCulture), + float.Parse(split[1].Trim(), Utils.EnUsCulture), + float.Parse(split[2].Trim(), Utils.EnUsCulture), + float.Parse(split[3].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector4 result) @@ -475,7 +444,7 @@ namespace OpenMetaverse public override string ToString() { - return String.Format(Helpers.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); + return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); } /// diff --git a/Programs/GridProxy/GridProxy.cs b/Programs/GridProxy/GridProxy.cs index f63f91f1..effeee72 100644 --- a/Programs/GridProxy/GridProxy.cs +++ b/Programs/GridProxy/GridProxy.cs @@ -535,7 +535,7 @@ namespace GridProxy reader.Read(content, 0, contentLength); #if DEBUG_CAPS - if (contentLength < 8192) Console.WriteLine("[" + reqNo + "] request length = " + contentLength + ":\n" + Helpers.FieldToUTF8String(content) + "\n-------------"); + if (contentLength < 8192) Console.WriteLine("[" + reqNo + "] request length = " + contentLength + ":\n" + Utils.BytesToString(content) + "\n-------------"); #endif if (uri == "/") @@ -1953,7 +1953,7 @@ namespace GridProxy TeleportFinishPacket tfp = (TeleportFinishPacket)packet; string simCaps = Encoding.UTF8.GetString(tfp.Info.SeedCapability).Replace("\0", ""); GenericCheck(ref tfp.Info.SimIP, ref tfp.Info.SimPort, ref simCaps, true); - tfp.Info.SeedCapability = Helpers.StringToField(simCaps); + tfp.Info.SeedCapability = Utils.StringToBytes(simCaps); return (Packet)tfp; } @@ -1972,7 +1972,7 @@ namespace GridProxy CrossedRegionPacket crp = (CrossedRegionPacket)packet; string simCaps = Encoding.UTF8.GetString(crp.RegionData.SeedCapability).Replace("\0", ""); GenericCheck(ref crp.RegionData.SimIP, ref crp.RegionData.SimPort, ref simCaps, true); - crp.RegionData.SeedCapability = Helpers.StringToField(simCaps); + crp.RegionData.SeedCapability = Utils.StringToBytes(simCaps); return (Packet)crp; } diff --git a/Programs/GridProxy/GridProxyLoader.cs b/Programs/GridProxy/GridProxyLoader.cs index f8d2de2b..fd984118 100644 --- a/Programs/GridProxy/GridProxyLoader.cs +++ b/Programs/GridProxy/GridProxyLoader.cs @@ -187,14 +187,14 @@ namespace GridProxy public void SayToUser(string message) { ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket(); - packet.ChatData.FromName = Helpers.StringToField("GridProxy"); + packet.ChatData.FromName = Utils.StringToBytes("GridProxy"); packet.ChatData.SourceID = UUID.Random(); packet.ChatData.OwnerID = agentID; packet.ChatData.SourceType = (byte)2; packet.ChatData.ChatType = (byte)1; packet.ChatData.Audible = (byte)1; packet.ChatData.Position = new Vector3(0, 0, 0); - packet.ChatData.Message = Helpers.StringToField(message); + packet.ChatData.Message = Utils.StringToBytes(message); proxy.InjectPacket(packet, Direction.Incoming); } diff --git a/Programs/GridProxy/Plugins/Analyst.cs b/Programs/GridProxy/Plugins/Analyst.cs index eba5ffb8..ae6a902c 100644 --- a/Programs/GridProxy/Plugins/Analyst.cs +++ b/Programs/GridProxy/Plugins/Analyst.cs @@ -412,14 +412,14 @@ public class Analyst : ProxyPlugin private void SayToUser(string message) { ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket(); - packet.ChatData.FromName = Helpers.StringToField("Analyst"); + packet.ChatData.FromName = Utils.StringToBytes("Analyst"); packet.ChatData.SourceID = UUID.Random(); packet.ChatData.OwnerID = frame.AgentID; packet.ChatData.SourceType = (byte)2; packet.ChatData.ChatType = (byte)1; packet.ChatData.Audible = (byte)1; packet.ChatData.Position = new Vector3(0, 0, 0); - packet.ChatData.Message = Helpers.StringToField(message); + packet.ChatData.Message = Utils.StringToBytes(message); proxy.InjectPacket(packet, Direction.Incoming); } @@ -537,7 +537,7 @@ public class Analyst : ProxyPlugin } else if (fieldClass == typeof(byte[])) { - return Helpers.StringToField(value); + return Utils.StringToBytes(value); } else if (fieldClass == typeof(Vector3)) { diff --git a/Programs/GridProxy/Plugins/ClientAO.cs b/Programs/GridProxy/Plugins/ClientAO.cs index a1d64ae5..d940fbd1 100644 --- a/Programs/GridProxy/Plugins/ClientAO.cs +++ b/Programs/GridProxy/Plugins/ClientAO.cs @@ -333,8 +333,8 @@ public class ClientAO : ProxyPlugin //look at them for (int i = 0; i < reply.FolderData.Length; i++) { - //SayToUser("Folder: " + Helpers.FieldToUTF8String(reply.FolderData[i].Name)); - if (searchPath[searchLevel] == Helpers.FieldToUTF8String(reply.FolderData[i].Name)) { + //SayToUser("Folder: " + Utils.BytesToString(reply.FolderData[i].Name)); + if (searchPath[searchLevel] == Utils.BytesToString(reply.FolderData[i].Name)) { //We found the next folder in the path currentFolder = reply.FolderData[i].FolderID; if (searchLevel < searchPath.Length - 1) @@ -393,10 +393,10 @@ public class ClientAO : ProxyPlugin item.CreatorID = reply.ItemData[i].CreatorID; item.AssetType = (AssetType)reply.ItemData[i].Type; item.AssetUUID = reply.ItemData[i].AssetID; - item.CreationDate = Helpers.UnixTimeToDateTime((uint)reply.ItemData[i].CreationDate); - item.Description = Helpers.FieldToUTF8String(reply.ItemData[i].Description); + item.CreationDate = Utils.UnixTimeToDateTime((uint)reply.ItemData[i].CreationDate); + item.Description = Utils.BytesToString(reply.ItemData[i].Description); item.Flags = (uint)reply.ItemData[i].Flags; - item.Name = Helpers.FieldToUTF8String(reply.ItemData[i].Name); + item.Name = Utils.BytesToString(reply.ItemData[i].Name); item.GroupID = reply.ItemData[i].GroupID; item.GroupOwned = reply.ItemData[i].GroupOwned; item.Permissions = new Permissions( @@ -511,14 +511,14 @@ public class ClientAO : ProxyPlugin private void SayToUser(string message) { ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket(); - packet.ChatData.FromName = Helpers.StringToField("ClientAO"); + packet.ChatData.FromName = Utils.StringToBytes("ClientAO"); packet.ChatData.SourceID = UUID.Random(); packet.ChatData.OwnerID = frame.AgentID; packet.ChatData.SourceType = (byte)2; packet.ChatData.ChatType = (byte)1; packet.ChatData.Audible = (byte)1; packet.ChatData.Position = new Vector3(0, 0, 0); - packet.ChatData.Message = Helpers.StringToField(message); + packet.ChatData.Message = Utils.StringToBytes(message); proxy.InjectPacket(packet, Direction.Incoming); } @@ -652,7 +652,7 @@ public class ClientAO : ProxyPlugin byte[] tmp = new byte[downloadedbytes]; Buffer.BlockCopy(buffer, 0, tmp, 0, downloadedbytes); buffer = tmp; - String notecardtext = getNotecardText(Helpers.FieldToUTF8String(buffer)); + String notecardtext = getNotecardText(Utils.BytesToString(buffer)); //Load config, wetikon format loadWetIkon(notecardtext); diff --git a/Programs/examples/GridAccountant/frmGridAccountant.cs b/Programs/examples/GridAccountant/frmGridAccountant.cs index 88bb3656..5d6e632a 100644 --- a/Programs/examples/GridAccountant/frmGridAccountant.cs +++ b/Programs/examples/GridAccountant/frmGridAccountant.cs @@ -382,7 +382,7 @@ namespace GridAccountant foreach (DirPeopleReplyPacket.QueryRepliesBlock block in reply.QueryReplies) { ListViewItem listItem = new ListViewItem(new string[] { - Helpers.FieldToUTF8String(block.FirstName) + " " + Helpers.FieldToUTF8String(block.LastName), + Utils.BytesToString(block.FirstName) + " " + Utils.BytesToString(block.LastName), (block.Online ? "Yes" : "No"), block.AgentID.ToString() }); this.BeginInvoke(new ListViewItemParamInvoker(AddFindItem), new object[] { listItem }); @@ -485,7 +485,7 @@ namespace GridAccountant query.QueryData.QueryFlags = 1; query.QueryData.QueryID = UUID.Random(); query.QueryData.QueryStart = 0; - query.QueryData.QueryText = Helpers.StringToField(txtFind.Text); + query.QueryData.QueryText = Utils.StringToBytes(txtFind.Text); query.Header.Reliable = true; Client.Network.SendPacket(query); diff --git a/Programs/examples/TestClient/Commands/Groups/ActivateGroupCommand.cs b/Programs/examples/TestClient/Commands/Groups/ActivateGroupCommand.cs index 1be5e943..78dd3bf9 100644 --- a/Programs/examples/TestClient/Commands/Groups/ActivateGroupCommand.cs +++ b/Programs/examples/TestClient/Commands/Groups/ActivateGroupCommand.cs @@ -85,7 +85,7 @@ namespace OpenMetaverse.TestClient AgentDataUpdatePacket p = (AgentDataUpdatePacket)packet; if (p.AgentData.AgentID == Client.Self.AgentID) { - activeGroup = Helpers.FieldToUTF8String(p.AgentData.GroupName) + " ( " + Helpers.FieldToUTF8String(p.AgentData.GroupTitle) + " )"; + activeGroup = Utils.BytesToString(p.AgentData.GroupName) + " ( " + Utils.BytesToString(p.AgentData.GroupTitle) + " )"; GroupsEvent.Set(); } } diff --git a/Programs/examples/TestClient/Commands/Movement/FollowCommand.cs b/Programs/examples/TestClient/Commands/Movement/FollowCommand.cs index cb9053bc..96678e2b 100644 --- a/Programs/examples/TestClient/Commands/Movement/FollowCommand.cs +++ b/Programs/examples/TestClient/Commands/Movement/FollowCommand.cs @@ -160,7 +160,7 @@ namespace OpenMetaverse.TestClient private void AlertMessageHandler(Packet packet, Simulator simulator) { AlertMessagePacket alert = (AlertMessagePacket)packet; - string message = Helpers.FieldToUTF8String(alert.AlertData.Message); + string message = Utils.BytesToString(alert.AlertData.Message); if (message.Contains("Autopilot cancel")) { diff --git a/Programs/examples/TestClient/Commands/System/MD5Command.cs b/Programs/examples/TestClient/Commands/System/MD5Command.cs index a880eff1..ed4aa375 100644 --- a/Programs/examples/TestClient/Commands/System/MD5Command.cs +++ b/Programs/examples/TestClient/Commands/System/MD5Command.cs @@ -15,7 +15,7 @@ namespace OpenMetaverse.TestClient public override string Execute(string[] args, UUID fromAgentID) { if (args.Length == 1) - return Helpers.MD5(args[0]); + return Utils.MD5(args[0]); else return "Usage: md5 [password]"; } diff --git a/Programs/examples/TestClient/TestClient.cs b/Programs/examples/TestClient/TestClient.cs index c72418a9..fdeb3b52 100644 --- a/Programs/examples/TestClient/TestClient.cs +++ b/Programs/examples/TestClient/TestClient.cs @@ -212,7 +212,7 @@ namespace OpenMetaverse.TestClient { AlertMessagePacket message = (AlertMessagePacket)packet; - Logger.Log("[AlertMessage] " + Helpers.FieldToUTF8String(message.AlertData.Message), Helpers.LogLevel.Info, this); + Logger.Log("[AlertMessage] " + Utils.BytesToString(message.AlertData.Message), Helpers.LogLevel.Info, this); } private void Self_OnInstantMessage(InstantMessage im, Simulator simulator) diff --git a/prebuild.xml b/prebuild.xml index f85424fb..74996e70 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -33,6 +33,26 @@ + + + + + ../../bin/ + + + + + ../../bin/ + OpenMetaverseTypes.XML + + + + ../../bin/ + + + + + @@ -53,8 +73,15 @@ + - + + + + + + + @@ -76,6 +103,7 @@ + @@ -99,6 +127,7 @@ + @@ -120,6 +149,7 @@ + @@ -143,6 +173,7 @@ ../bin/ + @@ -163,6 +194,7 @@ ../bin/ + @@ -187,6 +219,7 @@ + @@ -215,7 +248,8 @@ - + + @@ -241,6 +275,7 @@ + @@ -264,6 +299,7 @@ + @@ -308,6 +344,7 @@ + @@ -340,6 +377,7 @@ + @@ -365,6 +403,7 @@ + @@ -391,6 +430,7 @@ + @@ -414,6 +454,7 @@ + @@ -436,6 +477,7 @@ + @@ -457,6 +499,7 @@ ../../bin/ + @@ -484,6 +527,7 @@ + @@ -509,6 +553,7 @@ + @@ -534,6 +579,7 @@ + @@ -559,6 +605,7 @@ + @@ -581,6 +628,7 @@ ../../../bin/ + @@ -604,6 +652,7 @@ +