1
0

PGSQLSimulationData.cs 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Data;
  30. using System.Drawing;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Threading;
  34. using log4net;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Data;
  40. using Npgsql;
  41. namespace OpenSim.Data.PGSQL
  42. {
  43. /// <summary>
  44. /// A PGSQL Interface for the Region Server.
  45. /// </summary>
  46. public class PGSQLSimulationData : ISimulationDataStore
  47. {
  48. private const string _migrationStore = "RegionStore";
  49. private const string LogHeader = "[REGION DB PGSQL]";
  50. // private static FileSystemDataStore Instance = new FileSystemDataStore();
  51. private static readonly ILog _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. /// <summary>
  53. /// The database manager
  54. /// </summary>
  55. private PGSQLManager _Database;
  56. private string m_connectionString;
  57. protected virtual Assembly Assembly
  58. {
  59. get { return GetType().Assembly; }
  60. }
  61. public PGSQLSimulationData()
  62. {
  63. }
  64. public PGSQLSimulationData(string connectionString)
  65. {
  66. Initialise(connectionString);
  67. }
  68. /// <summary>
  69. /// Initialises the region datastore
  70. /// </summary>
  71. /// <param name="connectionString">The connection string.</param>
  72. public void Initialise(string connectionString)
  73. {
  74. m_connectionString = connectionString;
  75. _Database = new PGSQLManager(connectionString);
  76. using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
  77. {
  78. conn.Open();
  79. //New Migration settings
  80. Migration m = new Migration(conn, Assembly, "RegionStore");
  81. m.Update();
  82. }
  83. }
  84. /// <summary>
  85. /// Dispose the database
  86. /// </summary>
  87. public void Dispose() { }
  88. #region SceneObjectGroup region for loading and Store of the scene.
  89. /// <summary>
  90. /// Loads the objects present in the region.
  91. /// </summary>
  92. /// <param name="regionUUID">The region UUID.</param>
  93. /// <returns></returns>
  94. public List<SceneObjectGroup> LoadObjects(UUID regionUUID)
  95. {
  96. UUID lastGroupID = UUID.Zero;
  97. Dictionary<UUID, SceneObjectPart> prims = new Dictionary<UUID, SceneObjectPart>();
  98. Dictionary<UUID, SceneObjectGroup> objects = new Dictionary<UUID, SceneObjectGroup>();
  99. SceneObjectGroup grp = null;
  100. string sql = @"SELECT *,
  101. CASE WHEN prims.""UUID"" = prims.""SceneGroupID"" THEN 0 ELSE 1 END as sort
  102. FROM prims
  103. LEFT JOIN primshapes ON prims.""UUID"" = primshapes.""UUID""
  104. WHERE ""RegionUUID"" = :RegionUUID
  105. ORDER BY ""SceneGroupID"" asc, sort asc, ""LinkNumber"" asc";
  106. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  107. using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
  108. {
  109. command.Parameters.Add(_Database.CreateParameter("regionUUID", regionUUID));
  110. conn.Open();
  111. using (NpgsqlDataReader reader = command.ExecuteReader())
  112. {
  113. while (reader.Read())
  114. {
  115. SceneObjectPart sceneObjectPart = BuildPrim(reader);
  116. if (reader["Shape"] is DBNull)
  117. sceneObjectPart.Shape = PrimitiveBaseShape.Default;
  118. else
  119. sceneObjectPart.Shape = BuildShape(reader);
  120. prims[sceneObjectPart.UUID] = sceneObjectPart;
  121. UUID groupID = new UUID((Guid)reader["SceneGroupID"]);
  122. if (groupID != lastGroupID) // New SOG
  123. {
  124. if (grp != null)
  125. objects[grp.UUID] = grp;
  126. lastGroupID = groupID;
  127. // There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are
  128. // recorded as the root prim (for which the UUID must equal the persisted group UUID). In
  129. // this case, force the UUID to be the same as the group UUID so that at least these can be
  130. // deleted (we need to change the UUID so that any other prims in the linkset can also be
  131. // deleted).
  132. if (!groupID.IsZero() && sceneObjectPart.UUID.NotEqual(groupID))
  133. {
  134. _Log.WarnFormat(
  135. "[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID",
  136. sceneObjectPart.Name, sceneObjectPart.UUID, sceneObjectPart.GroupPosition, groupID);
  137. sceneObjectPart.UUID = groupID;
  138. }
  139. grp = new SceneObjectGroup(sceneObjectPart);
  140. if (reader["lnkstBinData"] is not DBNull)
  141. {
  142. byte[] data = (byte[])reader["lnkstBinData"];
  143. grp.LinksetData = LinksetData.FromBin(data);
  144. }
  145. }
  146. else
  147. {
  148. // Black magic to preserve link numbers
  149. // Why is this needed, fix this in AddPart method.
  150. int link = sceneObjectPart.LinkNum;
  151. grp.AddPart(sceneObjectPart);
  152. if (link != 0)
  153. sceneObjectPart.LinkNum = link;
  154. }
  155. }
  156. }
  157. }
  158. if (grp != null)
  159. objects[grp.UUID] = grp;
  160. // Instead of attempting to LoadItems on every prim,
  161. // most of which probably have no items... get a
  162. // list from DB of all prims which have items and
  163. // LoadItems only on those
  164. List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>();
  165. string qry = "select distinct \"primID\" from primitems";
  166. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  167. using (NpgsqlCommand command = new NpgsqlCommand(qry, conn))
  168. {
  169. conn.Open();
  170. using (NpgsqlDataReader itemReader = command.ExecuteReader())
  171. {
  172. while (itemReader.Read())
  173. {
  174. if (itemReader["primID"] is not DBNull)
  175. {
  176. if(UUID.TryParse(itemReader["primID"].ToString(), out UUID primID) &&
  177. prims.TryGetValue(primID, out SceneObjectPart sop))
  178. {
  179. primsWithInventory.Add(sop);
  180. }
  181. }
  182. }
  183. }
  184. }
  185. LoadItems(primsWithInventory);
  186. _Log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count);
  187. return new List<SceneObjectGroup>(objects.Values);
  188. }
  189. /// <summary>
  190. /// Load in the prim's persisted inventory.
  191. /// </summary>
  192. /// <param name="allPrims">all prims with inventory on a region</param>
  193. private void LoadItems(List<SceneObjectPart> allPrimsWithInventory)
  194. {
  195. string sql = @"SELECT * FROM primitems WHERE ""primID"" = :PrimID";
  196. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  197. using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
  198. {
  199. conn.Open();
  200. foreach (SceneObjectPart objectPart in allPrimsWithInventory)
  201. {
  202. command.Parameters.Clear();
  203. command.Parameters.Add(_Database.CreateParameter("PrimID", objectPart.UUID));
  204. List<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
  205. using (NpgsqlDataReader reader = command.ExecuteReader())
  206. {
  207. while (reader.Read())
  208. {
  209. TaskInventoryItem item = BuildItem(reader);
  210. item.ParentID = objectPart.UUID; // Values in database are
  211. // often wrong
  212. inventory.Add(item);
  213. }
  214. }
  215. objectPart.Inventory.RestoreInventoryItems(inventory);
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// Stores all object's details apart from inventory
  221. /// </summary>
  222. /// <param name="obj"></param>
  223. /// <param name="regionUUID"></param>
  224. public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
  225. {
  226. //_Log.DebugFormat("[PGSQL]: Adding/Changing SceneObjectGroup: {0} to region: {1}, object has {2} prims.", obj.UUID, regionUUID, obj.Parts.Length);
  227. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  228. {
  229. conn.Open();
  230. NpgsqlTransaction transaction = conn.BeginTransaction();
  231. try
  232. {
  233. foreach (SceneObjectPart sceneObjectPart in obj.Parts)
  234. {
  235. //Update prim
  236. using (NpgsqlCommand sqlCommand = conn.CreateCommand())
  237. {
  238. sqlCommand.Transaction = transaction;
  239. try
  240. {
  241. StoreSceneObjectPrim(sceneObjectPart, sqlCommand, obj.UUID, regionUUID);
  242. }
  243. catch (NpgsqlException sqlEx)
  244. {
  245. _Log.Error($"[REGION DB]: Store SceneObjectPrim SQL error: {sqlEx.Message}");
  246. throw;
  247. }
  248. }
  249. //Update primshapes
  250. using (NpgsqlCommand sqlCommand = conn.CreateCommand())
  251. {
  252. sqlCommand.Transaction = transaction;
  253. try
  254. {
  255. StoreSceneObjectPrimShapes(sceneObjectPart, sqlCommand, obj.UUID, regionUUID);
  256. }
  257. catch (NpgsqlException sqlEx)
  258. {
  259. _Log.Error($"[REGION DB]: Store SceneObjectPrimShapes SQL error: {sqlEx.Message}");
  260. throw;
  261. }
  262. }
  263. }
  264. transaction.Commit();
  265. }
  266. catch (Exception ex)
  267. {
  268. _Log.ErrorFormat("[REGION DB]: Store SceneObjectGroup error: {0}, Rolling back...", ex.Message);
  269. try
  270. {
  271. transaction.Rollback();
  272. }
  273. catch (Exception ex2)
  274. {
  275. //Show error
  276. _Log.InfoFormat("[REGION DB]: Rollback of SceneObjectGroup store transaction failed with error: {0}", ex2.Message);
  277. }
  278. }
  279. }
  280. }
  281. /// <summary>
  282. /// Stores the prim of the sceneobjectpart.
  283. /// </summary>
  284. /// <param name="sceneObjectPart">The sceneobjectpart or prim.</param>
  285. /// <param name="sqlCommand">The SQL command with the transaction.</param>
  286. /// <param name="sceneGroupID">The scenegroup UUID.</param>
  287. /// <param name="regionUUID">The region UUID.</param>
  288. private void StoreSceneObjectPrim(SceneObjectPart sceneObjectPart, NpgsqlCommand sqlCommand, UUID sceneGroupID, UUID regionUUID)
  289. {
  290. //Big query to update or insert a new prim.
  291. string queryPrims = @"
  292. UPDATE prims SET
  293. ""CreationDate"" = :CreationDate, ""Name"" = :Name, ""Text"" = :Text, ""Description"" = :Description, ""SitName"" = :SitName,
  294. ""TouchName"" = :TouchName, ""ObjectFlags"" = :ObjectFlags, ""OwnerMask"" = :OwnerMask, ""NextOwnerMask"" = :NextOwnerMask, ""GroupMask"" = :GroupMask,
  295. ""EveryoneMask"" = :EveryoneMask, ""BaseMask"" = :BaseMask, ""PositionX"" = :PositionX, ""PositionY"" = :PositionY, ""PositionZ"" = :PositionZ,
  296. ""GroupPositionX"" = :GroupPositionX, ""GroupPositionY"" = :GroupPositionY, ""GroupPositionZ"" = :GroupPositionZ, ""VelocityX"" = :VelocityX,
  297. ""VelocityY"" = :VelocityY, ""VelocityZ"" = :VelocityZ, ""AngularVelocityX"" = :AngularVelocityX, ""AngularVelocityY"" = :AngularVelocityY,
  298. ""AngularVelocityZ"" = :AngularVelocityZ, ""AccelerationX"" = :AccelerationX, ""AccelerationY"" = :AccelerationY,
  299. ""AccelerationZ"" = :AccelerationZ, ""RotationX"" = :RotationX, ""RotationY"" = :RotationY, ""RotationZ"" = :RotationZ, ""RotationW"" = :RotationW,
  300. ""SitTargetOffsetX"" = :SitTargetOffsetX, ""SitTargetOffsetY"" = :SitTargetOffsetY, ""SitTargetOffsetZ"" = :SitTargetOffsetZ,
  301. ""SitTargetOrientW"" = :SitTargetOrientW, ""SitTargetOrientX"" = :SitTargetOrientX, ""SitTargetOrientY"" = :SitTargetOrientY,
  302. ""SitTargetOrientZ"" = :SitTargetOrientZ, ""RegionUUID"" = :RegionUUID, ""CreatorID"" = :CreatorID, ""OwnerID"" = :OwnerID, ""GroupID"" = :GroupID,
  303. ""LastOwnerID"" = :LastOwnerID, ""SceneGroupID"" = :SceneGroupID, ""PayPrice"" = :PayPrice, ""PayButton1"" = :PayButton1, ""PayButton2"" = :PayButton2,
  304. ""PayButton3"" = :PayButton3, ""PayButton4"" = :PayButton4, ""LoopedSound"" = :LoopedSound, ""LoopedSoundGain"" = :LoopedSoundGain,
  305. ""TextureAnimation"" = :TextureAnimation, ""CameraEyeOffsetX"" = :CameraEyeOffsetX,
  306. ""CameraEyeOffsetY"" = :CameraEyeOffsetY, ""CameraEyeOffsetZ"" = :CameraEyeOffsetZ, ""CameraAtOffsetX"" = :CameraAtOffsetX,
  307. ""CameraAtOffsetY"" = :CameraAtOffsetY, ""CameraAtOffsetZ"" = :CameraAtOffsetZ, ""ForceMouselook"" = :ForceMouselook,
  308. ""ScriptAccessPin"" = :ScriptAccessPin, ""AllowedDrop"" = :AllowedDrop, ""DieAtEdge"" = :DieAtEdge, ""SalePrice"" = :SalePrice,
  309. ""PhysicsShapeType"" = :PhysicsShapeType, ""Density"" = :Density, ""GravityModifier"" = :GravityModifier, ""Friction"" = :Friction, ""Restitution"" = :Restitution,
  310. ""PassCollisions"" = :PassCollisions, ""RotationAxisLocks"" = :RotationAxisLocks, ""RezzerID"" = :RezzerID,
  311. ""ClickAction"" = :ClickAction, ""Material"" = :Material, ""CollisionSound"" = :CollisionSound, ""CollisionSoundVolume"" = :CollisionSoundVolume, ""PassTouches"" = :PassTouches,
  312. ""LinkNumber"" = :LinkNumber, ""MediaURL"" = :MediaURL, ""DynAttrs"" = :DynAttrs, ""Vehicle"" = :Vehicle,
  313. ""PhysInertia"" = :PhysInertia, ""standtargetx"" =:standtargetx, ""standtargety"" =:standtargety, ""standtargetz"" =:standtargetz,
  314. ""sitactrange"" =:sitactrange, ""pseudocrc"" = :pseudocrc, ""sopanims"" = :sopanims, ""lnkstBinData"" = :lnkstBinData
  315. WHERE ""UUID"" = :UUID ;
  316. INSERT INTO
  317. prims (
  318. ""UUID"", ""CreationDate"", ""Name"", ""Text"", ""Description"", ""SitName"", ""TouchName"", ""ObjectFlags"", ""OwnerMask"", ""NextOwnerMask"", ""GroupMask"",
  319. ""EveryoneMask"", ""BaseMask"", ""PositionX"", ""PositionY"", ""PositionZ"", ""GroupPositionX"", ""GroupPositionY"", ""GroupPositionZ"", ""VelocityX"",
  320. ""VelocityY"", ""VelocityZ"", ""AngularVelocityX"", ""AngularVelocityY"", ""AngularVelocityZ"", ""AccelerationX"", ""AccelerationY"", ""AccelerationZ"",
  321. ""RotationX"", ""RotationY"", ""RotationZ"", ""RotationW"", ""SitTargetOffsetX"", ""SitTargetOffsetY"", ""SitTargetOffsetZ"", ""SitTargetOrientW"",
  322. ""SitTargetOrientX"", ""SitTargetOrientY"", ""SitTargetOrientZ"", ""RegionUUID"", ""CreatorID"", ""OwnerID"", ""GroupID"", ""LastOwnerID"", ""SceneGroupID"",
  323. ""PayPrice"", ""PayButton1"", ""PayButton2"", ""PayButton3"", ""PayButton4"", ""LoopedSound"", ""LoopedSoundGain"", ""TextureAnimation"",
  324. ""CameraEyeOffsetX"", ""CameraEyeOffsetY"", ""CameraEyeOffsetZ"", ""CameraAtOffsetX"", ""CameraAtOffsetY"", ""CameraAtOffsetZ"",
  325. ""ForceMouselook"", ""ScriptAccessPin"", ""AllowedDrop"", ""DieAtEdge"", ""SalePrice"", ""SaleType"", ""ColorR"", ""ColorG"", ""ColorB"", ""ColorA"",
  326. ""ParticleSystem"", ""ClickAction"", ""Material"", ""CollisionSound"", ""CollisionSoundVolume"", ""PassTouches"", ""LinkNumber"", ""MediaURL"", ""DynAttrs"",
  327. ""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"", ""PassCollisions"", ""RotationAxisLocks"", ""RezzerID"" , ""Vehicle"", ""PhysInertia"",
  328. ""standtargetx"", ""standtargety"", ""standtargetz"", ""sitactrange"", ""pseudocrc"",""sopanims"",""lnkstBinData""
  329. ) Select
  330. :UUID, :CreationDate, :Name, :Text, :Description, :SitName, :TouchName, :ObjectFlags, :OwnerMask, :NextOwnerMask, :GroupMask,
  331. :EveryoneMask, :BaseMask, :PositionX, :PositionY, :PositionZ, :GroupPositionX, :GroupPositionY, :GroupPositionZ, :VelocityX,
  332. :VelocityY, :VelocityZ, :AngularVelocityX, :AngularVelocityY, :AngularVelocityZ, :AccelerationX, :AccelerationY, :AccelerationZ,
  333. :RotationX, :RotationY, :RotationZ, :RotationW, :SitTargetOffsetX, :SitTargetOffsetY, :SitTargetOffsetZ, :SitTargetOrientW,
  334. :SitTargetOrientX, :SitTargetOrientY, :SitTargetOrientZ, :RegionUUID, :CreatorID, :OwnerID, :GroupID, :LastOwnerID, :SceneGroupID,
  335. :PayPrice, :PayButton1, :PayButton2, :PayButton3, :PayButton4, :LoopedSound, :LoopedSoundGain, :TextureAnimation,
  336. :CameraEyeOffsetX, :CameraEyeOffsetY, :CameraEyeOffsetZ, :CameraAtOffsetX, :CameraAtOffsetY, :CameraAtOffsetZ,
  337. :ForceMouselook, :ScriptAccessPin, :AllowedDrop, :DieAtEdge, :SalePrice, :SaleType, :ColorR, :ColorG, :ColorB, :ColorA,
  338. :ParticleSystem, :ClickAction, :Material, :CollisionSound, :CollisionSoundVolume, :PassTouches, :LinkNumber, :MediaURL, :DynAttrs,
  339. :PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution, :PassCollisions, :RotationAxisLocks, :RezzerID, :Vehicle, :PhysInertia,
  340. :standtargetx, :standtargety, :standtargetz,:sitactrange, :pseudocrc, :sopanims, :lnkstBinData
  341. where not EXISTS (SELECT ""UUID"" FROM prims WHERE ""UUID"" = :UUID);
  342. ";
  343. //Set commandtext.
  344. sqlCommand.CommandText = queryPrims;
  345. //Add parameters
  346. sqlCommand.Parameters.AddRange(CreatePrimParameters(sceneObjectPart, sceneGroupID, regionUUID));
  347. //Execute the query. If it fails then error is trapped in calling function
  348. sqlCommand.ExecuteNonQuery();
  349. }
  350. /// <summary>
  351. /// Stores the scene object prim shapes.
  352. /// </summary>
  353. /// <param name="sceneObjectPart">The sceneobjectpart containing prim shape.</param>
  354. /// <param name="sqlCommand">The SQL command with the transaction.</param>
  355. /// <param name="sceneGroupID">The scenegroup UUID.</param>
  356. /// <param name="regionUUID">The region UUID.</param>
  357. private void StoreSceneObjectPrimShapes(SceneObjectPart sceneObjectPart, NpgsqlCommand sqlCommand, UUID sceneGroupID, UUID regionUUID)
  358. {
  359. //Big query to or insert or update primshapes
  360. string queryPrimShapes = @"
  361. UPDATE primshapes SET
  362. ""Shape"" = :Shape, ""ScaleX"" = :ScaleX, ""ScaleY"" = :ScaleY, ""ScaleZ"" = :ScaleZ, ""PCode"" = :PCode, ""PathBegin"" = :PathBegin,
  363. ""PathEnd"" = :PathEnd, ""PathScaleX"" = :PathScaleX, ""PathScaleY"" = :PathScaleY, ""PathShearX"" = :PathShearX, ""PathShearY"" = :PathShearY,
  364. ""PathSkew"" = :PathSkew, ""PathCurve"" = :PathCurve, ""PathRadiusOffset"" = :PathRadiusOffset, ""PathRevolutions"" = :PathRevolutions,
  365. ""PathTaperX"" = :PathTaperX, ""PathTaperY"" = :PathTaperY, ""PathTwist"" = :PathTwist, ""PathTwistBegin"" = :PathTwistBegin,
  366. ""ProfileBegin"" = :ProfileBegin, ""ProfileEnd"" = :ProfileEnd, ""ProfileCurve"" = :ProfileCurve, ""ProfileHollow"" = :ProfileHollow,
  367. ""Texture"" = :Texture, ""ExtraParams"" = :ExtraParams, ""State"" = :State, ""Media"" = :Media, ""MatOvrd"" = :MatOvrd
  368. WHERE ""UUID"" = :UUID ;
  369. INSERT INTO
  370. primshapes (
  371. ""UUID"", ""Shape"", ""ScaleX"", ""ScaleY"", ""ScaleZ"", ""PCode"", ""PathBegin"", ""PathEnd"", ""PathScaleX"", ""PathScaleY"", ""PathShearX"", ""PathShearY"",
  372. ""PathSkew"", ""PathCurve"", ""PathRadiusOffset"", ""PathRevolutions"", ""PathTaperX"", ""PathTaperY"", ""PathTwist"", ""PathTwistBegin"", ""ProfileBegin"",
  373. ""ProfileEnd"", ""ProfileCurve"", ""ProfileHollow"", ""Texture"", ""ExtraParams"", ""State"", ""Media"", ""MatOvrd""
  374. )
  375. Select
  376. :UUID, :Shape, :ScaleX, :ScaleY, :ScaleZ, :PCode, :PathBegin, :PathEnd, :PathScaleX, :PathScaleY, :PathShearX, :PathShearY,
  377. :PathSkew, :PathCurve, :PathRadiusOffset, :PathRevolutions, :PathTaperX, :PathTaperY, :PathTwist, :PathTwistBegin, :ProfileBegin,
  378. :ProfileEnd, :ProfileCurve, :ProfileHollow, :Texture, :ExtraParams, :State, :Media, :MatOvrd
  379. where not EXISTS (SELECT ""UUID"" FROM primshapes WHERE ""UUID"" = :UUID);
  380. ";
  381. //Set commandtext.
  382. sqlCommand.CommandText = queryPrimShapes;
  383. //Add parameters
  384. sqlCommand.Parameters.AddRange(CreatePrimShapeParameters(sceneObjectPart, sceneGroupID, regionUUID));
  385. //Execute the query. If it fails then error is trapped in calling function
  386. sqlCommand.ExecuteNonQuery();
  387. }
  388. /// <summary>
  389. /// Removes a object from the database.
  390. /// Meaning removing it from tables Prims, PrimShapes and PrimItems
  391. /// </summary>
  392. /// <param name="objectID">id of scenegroup</param>
  393. /// <param name="regionUUID">regionUUID (is this used anyway</param>
  394. public void RemoveObject(UUID objectID, UUID regionUUID)
  395. {
  396. //_Log.InfoFormat("[PGSQL]: Removing obj: {0} from region: {1}", objectID, regionUUID);
  397. //Remove from prims and primsitem table
  398. string sqlPrims = @"DELETE FROM PRIMS WHERE ""SceneGroupID"" = :objectID";
  399. string sqlPrimItems = @"DELETE FROM PRIMITEMS WHERE ""primID"" in (SELECT ""UUID"" FROM PRIMS WHERE ""SceneGroupID"" = :objectID)";
  400. string sqlPrimShapes = @"DELETE FROM PRIMSHAPES WHERE ""UUID"" in (SELECT ""UUID"" FROM PRIMS WHERE ""SceneGroupID"" = :objectID)";
  401. lock (_Database)
  402. {
  403. //Using the non transaction mode.
  404. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  405. using (NpgsqlCommand cmd = new NpgsqlCommand())
  406. {
  407. cmd.Connection = conn;
  408. cmd.CommandText = sqlPrimShapes;
  409. conn.Open();
  410. cmd.Parameters.Add(_Database.CreateParameter("objectID", objectID));
  411. cmd.ExecuteNonQuery();
  412. cmd.CommandText = sqlPrimItems;
  413. cmd.ExecuteNonQuery();
  414. cmd.CommandText = sqlPrims;
  415. cmd.ExecuteNonQuery();
  416. }
  417. }
  418. }
  419. /// <summary>
  420. /// Store the inventory of a prim. Warning deletes everything first and then adds all again.
  421. /// </summary>
  422. /// <param name="primID"></param>
  423. /// <param name="items"></param>
  424. public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
  425. {
  426. //_Log.InfoFormat("[REGION DB: Persisting Prim Inventory with prim ID {0}", primID);
  427. //Statement from PGSQL section!
  428. // For now, we're just going to crudely remove all the previous inventory items
  429. // no matter whether they have changed or not, and replace them with the current set.
  430. //Delete everything from PrimID
  431. //TODO add index on PrimID in DB, if not already exist
  432. string sql = @"delete from primitems where ""primID"" = :primID";
  433. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  434. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  435. {
  436. cmd.Parameters.Add(_Database.CreateParameter("primID", primID));
  437. conn.Open();
  438. cmd.ExecuteNonQuery();
  439. }
  440. sql =
  441. @"INSERT INTO primitems (
  442. ""itemID"",""primID"",""assetID"",""parentFolderID"",""invType"",""assetType"",""name"",""description"",""creationDate"",""creatorID"",""ownerID"",""lastOwnerID"",""groupID"",
  443. ""nextPermissions"",""currentPermissions"",""basePermissions"",""everyonePermissions"",""groupPermissions"",""flags"")
  444. VALUES (:itemID,:primID,:assetID,:parentFolderID,:invType,:assetType,:name,:description,:creationDate,:creatorID,:ownerID,
  445. :lastOwnerID,:groupID,:nextPermissions,:currentPermissions,:basePermissions,:everyonePermissions,:groupPermissions,:flags)";
  446. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  447. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  448. {
  449. conn.Open();
  450. foreach (TaskInventoryItem taskItem in items)
  451. {
  452. cmd.Parameters.AddRange(CreatePrimInventoryParameters(taskItem));
  453. cmd.ExecuteNonQuery();
  454. cmd.Parameters.Clear();
  455. }
  456. }
  457. }
  458. #endregion
  459. /// <summary>
  460. /// Loads the terrain map.
  461. /// </summary>
  462. /// <param name="regionID">regionID.</param>
  463. /// <returns></returns>
  464. public double[,] LoadTerrain(UUID regionID)
  465. {
  466. double[,] ret = null;
  467. TerrainData terrData = LoadTerrain(regionID, (int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionHeight);
  468. if (terrData != null)
  469. ret = terrData.GetDoubles();
  470. return ret;
  471. }
  472. // Returns 'null' if region not found
  473. public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
  474. {
  475. TerrainData terrData = null;
  476. string sql = @"select ""RegionUUID"", ""Revision"", ""Heightfield"" from terrain
  477. where ""RegionUUID"" = :RegionUUID order by ""Revision"" desc limit 1; ";
  478. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  479. {
  480. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  481. {
  482. // PGSqlParameter param = new PGSqlParameter();
  483. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID));
  484. conn.Open();
  485. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  486. {
  487. int rev;
  488. if (reader.Read())
  489. {
  490. rev = Convert.ToInt32(reader["Revision"]);
  491. if ((reader["Heightfield"] != DBNull.Value))
  492. {
  493. byte[] blob = (byte[])reader["Heightfield"];
  494. terrData = TerrainData.CreateFromDatabaseBlobFactory(pSizeX, pSizeY, pSizeZ, rev, blob);
  495. }
  496. }
  497. else
  498. {
  499. _Log.Info("[REGION DB]: No terrain found for region");
  500. return null;
  501. }
  502. _Log.Info("[REGION DB]: Loaded terrain revision r" + rev);
  503. }
  504. }
  505. }
  506. return terrData;
  507. }
  508. public TerrainData LoadBakedTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
  509. {
  510. TerrainData terrData = null;
  511. string sql = @"select ""RegionUUID"", ""Revision"", ""Heightfield"" from bakedterrain
  512. where ""RegionUUID"" = :RegionUUID; ";
  513. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  514. {
  515. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  516. {
  517. // PGSqlParameter param = new PGSqlParameter();
  518. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID));
  519. conn.Open();
  520. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  521. {
  522. int rev;
  523. if (reader.Read())
  524. {
  525. rev = Convert.ToInt32(reader["Revision"]);
  526. if ((reader["Heightfield"] != DBNull.Value))
  527. {
  528. byte[] blob = (byte[])reader["Heightfield"];
  529. terrData = TerrainData.CreateFromDatabaseBlobFactory(pSizeX, pSizeY, pSizeZ, rev, blob);
  530. }
  531. }
  532. }
  533. }
  534. }
  535. return terrData;
  536. }
  537. // Legacy entry point for when terrain was always a 256x256 heightmap
  538. public void StoreTerrain(double[,] terrain, UUID regionID)
  539. {
  540. StoreTerrain(new TerrainData(terrain), regionID);
  541. }
  542. /// <summary>
  543. /// Stores the terrain map to DB.
  544. /// </summary>
  545. /// <param name="terrain">terrain map data.</param>
  546. /// <param name="regionID">regionID.</param>
  547. public void StoreTerrain(TerrainData terrData, UUID regionID)
  548. {
  549. //Delete old terrain map
  550. string sql = @"delete from terrain where ""RegionUUID""=:RegionUUID";
  551. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  552. {
  553. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  554. {
  555. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID));
  556. conn.Open();
  557. cmd.ExecuteNonQuery();
  558. _Log.InfoFormat("{0} Deleted terrain revision id = {1}", LogHeader, regionID);
  559. }
  560. }
  561. int terrainDBRevision;
  562. Array terrainDBblob;
  563. terrData.GetDatabaseBlob(out terrainDBRevision, out terrainDBblob);
  564. sql = @"insert into terrain(""RegionUUID"", ""Revision"", ""Heightfield"") values(:RegionUUID, :Revision, :Heightfield)";
  565. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  566. {
  567. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  568. {
  569. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID));
  570. cmd.Parameters.Add(_Database.CreateParameter("Revision", terrainDBRevision));
  571. cmd.Parameters.Add(_Database.CreateParameter("Heightfield", terrainDBblob));
  572. conn.Open();
  573. cmd.ExecuteNonQuery();
  574. _Log.InfoFormat("{0} Stored terrain id = {1}, terrainSize = <{2},{3}>",
  575. LogHeader, regionID, terrData.SizeX, terrData.SizeY);
  576. }
  577. }
  578. }
  579. /// <summary>
  580. /// Stores the baked terrain map to DB.
  581. /// </summary>
  582. /// <param name="terrain">terrain map data.</param>
  583. /// <param name="regionID">regionID.</param>
  584. public void StoreBakedTerrain(TerrainData terrData, UUID regionID)
  585. {
  586. //Delete old terrain map
  587. string sql = @"delete from bakedterrain where ""RegionUUID""=:RegionUUID";
  588. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  589. {
  590. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  591. {
  592. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID));
  593. conn.Open();
  594. cmd.ExecuteNonQuery();
  595. _Log.InfoFormat("{0} Deleted bakedterrain id = {1}", LogHeader, regionID);
  596. }
  597. }
  598. int terrainDBRevision;
  599. Array terrainDBblob;
  600. terrData.GetDatabaseBlob(out terrainDBRevision, out terrainDBblob);
  601. sql = @"insert into bakedterrain(""RegionUUID"", ""Revision"", ""Heightfield"") values(:RegionUUID, :Revision, :Heightfield)";
  602. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  603. {
  604. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  605. {
  606. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionID));
  607. cmd.Parameters.Add(_Database.CreateParameter("Revision", terrainDBRevision));
  608. cmd.Parameters.Add(_Database.CreateParameter("Heightfield", terrainDBblob));
  609. conn.Open();
  610. cmd.ExecuteNonQuery();
  611. _Log.InfoFormat("{0} Stored bakedterrain id = {1}, terrainSize = <{2},{3}>",
  612. LogHeader, regionID, terrData.SizeX, terrData.SizeY);
  613. }
  614. }
  615. }
  616. /// <summary>
  617. /// Loads all the land objects of a region.
  618. /// </summary>
  619. /// <param name="regionUUID">The region UUID.</param>
  620. /// <returns></returns>
  621. public List<LandData> LoadLandObjects(UUID regionUUID)
  622. {
  623. List<LandData> LandDataForRegion = new List<LandData>();
  624. string sql = @"select * from land where ""RegionUUID"" = :RegionUUID";
  625. //Retrieve all land data from region
  626. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  627. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  628. {
  629. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID));
  630. conn.Open();
  631. using (NpgsqlDataReader readerLandData = cmd.ExecuteReader())
  632. {
  633. while (readerLandData.Read())
  634. {
  635. LandDataForRegion.Add(BuildLandData(readerLandData));
  636. }
  637. }
  638. }
  639. //Retrieve all accesslist data for all landdata
  640. foreach (LandData LandData in LandDataForRegion)
  641. {
  642. sql = @"select * from landaccesslist where ""LandUUID"" = :LandUUID";
  643. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  644. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  645. {
  646. cmd.Parameters.Add(_Database.CreateParameter("LandUUID", LandData.GlobalID));
  647. conn.Open();
  648. using (NpgsqlDataReader readerAccessList = cmd.ExecuteReader())
  649. {
  650. while (readerAccessList.Read())
  651. {
  652. LandData.ParcelAccessList.Add(BuildLandAccessData(readerAccessList));
  653. }
  654. }
  655. }
  656. }
  657. //Return data
  658. return LandDataForRegion;
  659. }
  660. /// <summary>
  661. /// Stores land object with landaccess list.
  662. /// </summary>
  663. /// <param name="parcel">parcel data.</param>
  664. public void StoreLandObject(ILandObject parcel)
  665. {
  666. //As this is only one record in land table I just delete all and then add a new record.
  667. //As the delete landaccess is already in the pgsql code
  668. //Delete old values
  669. RemoveLandObject(parcel.LandData.GlobalID);
  670. //Insert new values
  671. string sql = @"INSERT INTO land
  672. (""UUID"",""RegionUUID"",""LocalLandID"",""Bitmap"",""Name"",""Description"",""OwnerUUID"",""IsGroupOwned"",""Area"",""AuctionID"",""Category"",""ClaimDate"",""ClaimPrice"",
  673. ""GroupUUID"",""SalePrice"",""LandStatus"",""LandFlags"",""LandingType"",""MediaAutoScale"",""MediaTextureUUID"",""MediaURL"",""MusicURL"",""PassHours"",""PassPrice"",
  674. ""SnapshotUUID"",""UserLocationX"",""UserLocationY"",""UserLocationZ"",""UserLookAtX"",""UserLookAtY"",""UserLookAtZ"",""AuthbuyerID"",""OtherCleanTime"",""Dwell"",
  675. ""MediaType"",""MediaDescription"",""MediaSize"",""MediaLoop"",""ObscureMusic"",""ObscureMedia"",""SeeAVs"",""AnyAVSounds"",""GroupAVSounds"",
  676. ""environment"")
  677. VALUES
  678. (:UUID,:RegionUUID,:LocalLandID,:Bitmap,:Name,:Description,:OwnerUUID,:IsGroupOwned,:Area,:AuctionID,:Category,:ClaimDate,:ClaimPrice,
  679. :GroupUUID,:SalePrice,:LandStatus,:LandFlags,:LandingType,:MediaAutoScale,:MediaTextureUUID,:MediaURL,:MusicURL,:PassHours,:PassPrice,
  680. :SnapshotUUID,:UserLocationX,:UserLocationY,:UserLocationZ,:UserLookAtX,:UserLookAtY,:UserLookAtZ,:AuthbuyerID,:OtherCleanTime,:Dwell,
  681. :MediaType,:MediaDescription,:MediaWidth::text || ',' || :MediaHeight::text,:MediaLoop,:ObscureMusic,:ObscureMedia,:SeeAVs::int::smallint,
  682. :AnyAVSounds::int::smallint,:GroupAVSounds::int::smallint,:environment)";
  683. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  684. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  685. {
  686. cmd.Parameters.AddRange(CreateLandParameters(parcel.LandData, parcel.RegionUUID));
  687. conn.Open();
  688. cmd.ExecuteNonQuery();
  689. }
  690. sql = @"INSERT INTO landaccesslist (""LandUUID"",""AccessUUID"",""Flags"",""Expires"") VALUES (:LandUUID,:AccessUUID,:Flags,:Expires)";
  691. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  692. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  693. {
  694. conn.Open();
  695. foreach (LandAccessEntry parcelAccessEntry in parcel.LandData.ParcelAccessList)
  696. {
  697. cmd.Parameters.AddRange(CreateLandAccessParameters(parcelAccessEntry, parcel.RegionUUID));
  698. cmd.ExecuteNonQuery();
  699. cmd.Parameters.Clear();
  700. }
  701. }
  702. }
  703. /// <summary>
  704. /// Removes a land object from DB.
  705. /// </summary>
  706. /// <param name="globalID">UUID of landobject</param>
  707. public void RemoveLandObject(UUID globalID)
  708. {
  709. string sql = @"delete from land where ""UUID""=:UUID";
  710. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  711. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  712. {
  713. cmd.Parameters.Add(_Database.CreateParameter("UUID", globalID));
  714. conn.Open();
  715. cmd.ExecuteNonQuery();
  716. }
  717. sql = @"delete from landaccesslist where ""LandUUID""=:UUID";
  718. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  719. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  720. {
  721. cmd.Parameters.Add(_Database.CreateParameter("UUID", globalID));
  722. conn.Open();
  723. cmd.ExecuteNonQuery();
  724. }
  725. }
  726. #region Environment Settings
  727. public string LoadRegionEnvironmentSettings(UUID regionUUID)
  728. {
  729. string sql = "select * from regionenvironment where region_id = :region_id";
  730. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  731. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  732. {
  733. cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID));
  734. conn.Open();
  735. using (NpgsqlDataReader result = cmd.ExecuteReader())
  736. {
  737. if (!result.Read())
  738. {
  739. return String.Empty;
  740. }
  741. else
  742. {
  743. return Convert.ToString(result["llsd_settings"]);
  744. }
  745. }
  746. }
  747. }
  748. public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings)
  749. {
  750. {
  751. string sql = "DELETE FROM regionenvironment WHERE region_id = :region_id ;";
  752. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  753. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  754. {
  755. cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID));
  756. conn.Open();
  757. cmd.ExecuteNonQuery();
  758. }
  759. sql = "INSERT INTO regionenvironment (region_id, llsd_settings) VALUES (:region_id, :llsd_settings) ;";
  760. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  761. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  762. {
  763. cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID));
  764. cmd.Parameters.Add(_Database.CreateParameter("llsd_settings", settings));
  765. conn.Open();
  766. cmd.ExecuteNonQuery();
  767. }
  768. }
  769. }
  770. public void RemoveRegionEnvironmentSettings(UUID regionUUID)
  771. {
  772. string sql = "delete from regionenvironment where region_id = :region_id ;";
  773. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  774. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  775. {
  776. cmd.Parameters.Add(_Database.CreateParameter("region_id", regionUUID));
  777. conn.Open();
  778. cmd.ExecuteNonQuery();
  779. }
  780. }
  781. #endregion
  782. /// <summary>
  783. /// Loads the settings of a region.
  784. /// </summary>
  785. /// <param name="regionUUID">The region UUID.</param>
  786. /// <returns></returns>
  787. public RegionSettings LoadRegionSettings(UUID regionUUID)
  788. {
  789. string sql = @"select * from regionsettings where ""regionUUID"" = :regionUUID";
  790. RegionSettings regionSettings = null;
  791. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  792. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  793. {
  794. cmd.Parameters.Add(_Database.CreateParameter("regionUUID", regionUUID));
  795. conn.Open();
  796. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  797. {
  798. if (reader.Read())
  799. {
  800. regionSettings = BuildRegionSettings(reader);
  801. regionSettings.OnSave += StoreRegionSettings;
  802. }
  803. }
  804. if (regionSettings != null)
  805. {
  806. LoadSpawnPoints(regionSettings);
  807. return regionSettings;
  808. }
  809. }
  810. //If we reach this point then there are new region settings for that region
  811. regionSettings = new RegionSettings();
  812. regionSettings.RegionUUID = regionUUID;
  813. regionSettings.OnSave += StoreRegionSettings;
  814. //Store new values
  815. // StoreNewRegionSettings(regionSettings);
  816. StoreRegionSettings(regionSettings);
  817. LoadSpawnPoints(regionSettings);
  818. return regionSettings;
  819. }
  820. /// <summary>
  821. /// Store region settings
  822. /// </summary>
  823. /// <param name="regionSettings">region settings.</param>
  824. public void StoreRegionSettings(RegionSettings regionSettings)
  825. {
  826. const string queryString = """
  827. INSERT INTO regionsettings ( "regionUUID", block_terraform, block_fly, allow_damage, restrict_pushing,
  828. allow_land_resell, allow_land_join_divide, block_show_in_search, agent_limit, object_bonus,
  829. maturity, disable_scripts, disable_collisions, disable_physics, terrain_texture_1, terrain_texture_2,
  830. terrain_texture_3, terrain_texture_4, elevation_1_nw, elevation_2_nw, elevation_1_ne, elevation_2_ne,
  831. elevation_1_se, elevation_2_se, elevation_1_sw, elevation_2_sw, water_height, terrain_raise_limit,
  832. terrain_lower_limit, use_estate_sun, fixed_sun, sun_position, covenant, covenant_datetime, "Sandbox",
  833. sunvectorx, sunvectory, sunvectorz, loaded_creation_datetime, loaded_creation_id, "map_tile_ID",
  834. block_search, casino, "TelehubObject", "parcel_tile_ID", "cacheID", "TerrainPBR1", "TerrainPBR2",
  835. "TerrainPBR3", "TerrainPBR4")
  836. VALUES
  837. (:RegionUUID, :block_terraform, :block_fly, :allow_damage, :restrict_pushing, :allow_land_resell,
  838. :allow_land_join_divide, :block_show_in_search, :agent_limit, :object_bonus, :maturity, :disable_scripts,
  839. :disable_collisions, :disable_physics, :terrain_texture_1, :terrain_texture_2, :terrain_texture_3,
  840. :terrain_texture_4, :elevation_1_nw, :elevation_2_nw, :elevation_1_ne, :elevation_2_ne, :elevation_1_se,
  841. :elevation_2_se, :elevation_1_sw, :elevation_2_sw, :water_height, :terrain_raise_limit, :terrain_lower_limit,
  842. :use_estate_sun, :fixed_sun, :sun_position, :covenant, :covenant_datetime, :Sandbox, :sunvectorx,
  843. :sunvectory, :sunvectorz, :Loaded_Creation_DateTime, :Loaded_Creation_ID, :map_tile_ID,
  844. :block_search, :casino, :TelehubObject, :ParcelImageID, :cacheID, :TerrainPBR1, :TerrainPBR2,
  845. :TerrainPBR3, :TerrainPBR4)
  846. ON CONFLICT ("regionUUID")
  847. DO UPDATE SET "regionUUID" = :RegionUUID, block_terraform = :block_terraform, block_fly = :block_fly,
  848. allow_damage = :allow_damage, restrict_pushing = :restrict_pushing, allow_land_resell = :allow_land_resell,
  849. allow_land_join_divide = :allow_land_join_divide, block_show_in_search = :block_show_in_search,
  850. agent_limit = :agent_limit, object_bonus = :object_bonus, maturity = :maturity, disable_scripts = :disable_scripts,
  851. disable_collisions = :disable_collisions, disable_physics = :disable_physics, terrain_texture_1 = :terrain_texture_1,
  852. terrain_texture_2 = :terrain_texture_2, terrain_texture_3 = :terrain_texture_3, terrain_texture_4 = :terrain_texture_4,
  853. elevation_1_nw = :elevation_1_nw, elevation_2_nw = :elevation_2_nw, elevation_1_ne = :elevation_1_ne,
  854. elevation_2_ne = :elevation_2_ne, elevation_1_se = :elevation_1_se, elevation_2_se = :elevation_2_se,
  855. elevation_1_sw = :elevation_1_sw, elevation_2_sw = :elevation_2_sw, water_height = :water_height,
  856. terrain_raise_limit = :terrain_raise_limit, terrain_lower_limit = :terrain_lower_limit,
  857. use_estate_sun = :use_estate_sun, fixed_sun = :fixed_sun, sun_position = :sun_position, covenant = :covenant,
  858. covenant_datetime = :covenant_datetime, "Sandbox" = :Sandbox, sunvectorx = :sunvectorx,
  859. sunvectory = :sunvectory, sunvectorz = :sunvectorz, loaded_creation_datetime = :Loaded_Creation_DateTime,
  860. loaded_creation_id = :Loaded_Creation_ID, "map_tile_ID" = :map_tile_ID, block_search = :block_search,
  861. casino = :casino, "TelehubObject" = :TelehubObject, "parcel_tile_ID" = :ParcelImageID, "cacheID" = :cacheID,
  862. "TerrainPBR1" = :TerrainPBR1, "TerrainPBR2" = :TerrainPBR2, "TerrainPBR3" = :TerrainPBR3,
  863. "TerrainPBR4" = :TerrainPBR4
  864. """;
  865. using (var connection = new NpgsqlConnection(m_connectionString))
  866. {
  867. connection.Open();
  868. NpgsqlCommand command = new NpgsqlCommand(queryString, connection, connection.BeginTransaction());
  869. using (command)
  870. {
  871. try
  872. {
  873. command.Parameters.AddRange(CreateRegionSettingParameters(regionSettings));
  874. command.ExecuteNonQuery();
  875. command.Transaction.Commit();
  876. }
  877. catch (Exception e)
  878. {
  879. Console.WriteLine(e);
  880. command.Transaction.Rollback();
  881. throw;
  882. }
  883. }
  884. }
  885. SaveSpawnPoints(regionSettings);
  886. }
  887. public void Shutdown()
  888. {
  889. //Not used??
  890. }
  891. #region Private DataRecord conversion methods
  892. /// <summary>
  893. /// Builds the region settings from a datarecod.
  894. /// </summary>
  895. /// <param name="row">datarecord with regionsettings.</param>
  896. /// <returns></returns>
  897. private static RegionSettings BuildRegionSettings(IDataRecord row)
  898. {
  899. //TODO change this is some more generic code so we doesnt have to change it every time a new field is added?
  900. RegionSettings newSettings = new RegionSettings();
  901. newSettings.RegionUUID = new UUID((Guid)row["regionUUID"]);
  902. newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]);
  903. newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]);
  904. newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]);
  905. newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]);
  906. newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]);
  907. newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]);
  908. newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]);
  909. newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]);
  910. newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]);
  911. newSettings.Maturity = Convert.ToInt32(row["maturity"]);
  912. newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]);
  913. newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]);
  914. newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]);
  915. newSettings.TerrainTexture1 = new UUID((Guid)row["terrain_texture_1"]);
  916. newSettings.TerrainTexture2 = new UUID((Guid)row["terrain_texture_2"]);
  917. newSettings.TerrainTexture3 = new UUID((Guid)row["terrain_texture_3"]);
  918. newSettings.TerrainTexture4 = new UUID((Guid)row["terrain_texture_4"]);
  919. newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]);
  920. newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]);
  921. newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]);
  922. newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]);
  923. newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]);
  924. newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]);
  925. newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]);
  926. newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]);
  927. newSettings.WaterHeight = Convert.ToDouble(row["water_height"]);
  928. newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]);
  929. newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]);
  930. newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]);
  931. newSettings.Sandbox = Convert.ToBoolean(row["Sandbox"]);
  932. newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]);
  933. newSettings.SunPosition = Convert.ToDouble(row["sun_position"]);
  934. newSettings.SunVector = new Vector3(
  935. Convert.ToSingle(row["sunvectorx"]),
  936. Convert.ToSingle(row["sunvectory"]),
  937. Convert.ToSingle(row["sunvectorz"])
  938. );
  939. newSettings.Covenant = new UUID((Guid)row["covenant"]);
  940. newSettings.CovenantChangedDateTime = Convert.ToInt32(row["covenant_datetime"]);
  941. newSettings.LoadedCreationDateTime = Convert.ToInt32(row["loaded_creation_datetime"]);
  942. if (row["loaded_creation_id"] is DBNull)
  943. newSettings.LoadedCreationID = "";
  944. else
  945. newSettings.LoadedCreationID = (String)row["loaded_creation_id"];
  946. newSettings.TerrainImageID = new UUID((string)row["map_tile_ID"]);
  947. newSettings.ParcelImageID = new UUID((Guid)row["parcel_tile_ID"]);
  948. newSettings.TelehubObject = new UUID((Guid)row["TelehubObject"]);
  949. if (!(row["cacheID"] is DBNull))
  950. newSettings.CacheID = new UUID((Guid)row["cacheID"]);
  951. newSettings.TerrainPBR1 = new UUID((Guid)row["TerrainPBR1"]);
  952. newSettings.TerrainPBR2 = new UUID((Guid)row["TerrainPBR2"]);
  953. newSettings.TerrainPBR3 = new UUID((Guid)row["TerrainPBR3"]);
  954. newSettings.TerrainPBR4 = new UUID((Guid)row["TerrainPBR4"]);
  955. return newSettings;
  956. }
  957. /// <summary>
  958. /// Builds the land data from a datarecord.
  959. /// </summary>
  960. /// <param name="row">datarecord with land data</param>
  961. /// <returns></returns>
  962. private static LandData BuildLandData(IDataRecord row)
  963. {
  964. LandData newData = new LandData();
  965. newData.GlobalID = new UUID((Guid)row["UUID"]);
  966. newData.LocalID = Convert.ToInt32(row["LocalLandID"]);
  967. // Bitmap is a byte[512]
  968. newData.Bitmap = (Byte[])row["Bitmap"];
  969. newData.Name = (string)row["Name"];
  970. newData.Description = (string)row["Description"];
  971. newData.OwnerID = new UUID((Guid)row["OwnerUUID"]);
  972. newData.IsGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]);
  973. newData.Area = Convert.ToInt32(row["Area"]);
  974. newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented
  975. newData.Category = (ParcelCategory)Convert.ToInt32(row["Category"]);
  976. //Enum libsecondlife.Parcel.ParcelCategory
  977. newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]);
  978. newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]);
  979. newData.GroupID = new UUID((Guid)row["GroupUUID"]);
  980. newData.SalePrice = Convert.ToInt32(row["SalePrice"]);
  981. newData.Status = (ParcelStatus)Convert.ToInt32(row["LandStatus"]);
  982. //Enum. libsecondlife.Parcel.ParcelStatus
  983. newData.Flags = Convert.ToUInt32(row["LandFlags"]);
  984. newData.LandingType = Convert.ToByte(row["LandingType"]);
  985. newData.MediaAutoScale = Convert.ToByte(row["MediaAutoScale"]);
  986. newData.MediaID = new UUID((Guid)row["MediaTextureUUID"]);
  987. newData.MediaURL = (string)row["MediaURL"];
  988. newData.MusicURL = (string)row["MusicURL"];
  989. newData.PassHours = Convert.ToSingle(row["PassHours"]);
  990. newData.PassPrice = Convert.ToInt32(row["PassPrice"]);
  991. // UUID authedbuyer;
  992. // UUID snapshotID;
  993. //
  994. // if (UUID.TryParse((string)row["AuthBuyerID"], out authedbuyer))
  995. // newData.AuthBuyerID = authedbuyer;
  996. //
  997. // if (UUID.TryParse((string)row["SnapshotUUID"], out snapshotID))
  998. // newData.SnapshotID = snapshotID;
  999. newData.AuthBuyerID = new UUID((Guid)row["AuthBuyerID"]);
  1000. newData.SnapshotID = new UUID((Guid)row["SnapshotUUID"]);
  1001. newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
  1002. newData.Dwell = Convert.ToSingle(row["Dwell"]);
  1003. try
  1004. {
  1005. newData.UserLocation =
  1006. new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]),
  1007. Convert.ToSingle(row["UserLocationZ"]));
  1008. newData.UserLookAt =
  1009. new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]),
  1010. Convert.ToSingle(row["UserLookAtZ"]));
  1011. }
  1012. catch (InvalidCastException)
  1013. {
  1014. newData.UserLocation = Vector3.Zero;
  1015. newData.UserLookAt = Vector3.Zero;
  1016. _Log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name);
  1017. }
  1018. newData.ParcelAccessList = new List<LandAccessEntry>();
  1019. newData.MediaDescription = (string)row["MediaDescription"];
  1020. newData.MediaType = (string)row["MediaType"];
  1021. string[] sizes = ((string)row["MediaSize"]).Split(',');
  1022. if (sizes.Length > 1)
  1023. {
  1024. newData.MediaWidth = Convert.ToInt32(sizes[0]);
  1025. newData.MediaHeight = Convert.ToInt32(sizes[1]);
  1026. }
  1027. newData.MediaLoop = Convert.ToBoolean(row["MediaLoop"]);
  1028. newData.ObscureMusic = Convert.ToBoolean(row["ObscureMusic"]);
  1029. newData.ObscureMedia = Convert.ToBoolean(row["ObscureMedia"]);
  1030. newData.SeeAVs = Convert.ToBoolean(row["SeeAVs"]);
  1031. newData.AnyAVSounds = Convert.ToBoolean(row["AnyAVSounds"]);
  1032. newData.GroupAVSounds = Convert.ToBoolean(row["GroupAVSounds"]);
  1033. if (row["environment"] is DBNull)
  1034. {
  1035. newData.Environment = null;
  1036. newData.EnvironmentVersion = -1;
  1037. }
  1038. else
  1039. {
  1040. string env = (string)row["environment"];
  1041. if (string.IsNullOrEmpty(env))
  1042. {
  1043. newData.Environment = null;
  1044. newData.EnvironmentVersion = -1;
  1045. }
  1046. else
  1047. {
  1048. try
  1049. {
  1050. ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
  1051. newData.Environment = VEnv;
  1052. newData.EnvironmentVersion = VEnv.version;
  1053. }
  1054. catch
  1055. {
  1056. newData.Environment = null;
  1057. newData.EnvironmentVersion = -1;
  1058. }
  1059. }
  1060. }
  1061. return newData;
  1062. }
  1063. /// <summary>
  1064. /// Builds the landaccess data from a data record.
  1065. /// </summary>
  1066. /// <param name="row">datarecord with landaccess data</param>
  1067. /// <returns></returns>
  1068. private static LandAccessEntry BuildLandAccessData(IDataRecord row)
  1069. {
  1070. LandAccessEntry entry = new LandAccessEntry();
  1071. entry.AgentID = new UUID((Guid)row["AccessUUID"]);
  1072. entry.Flags = (AccessList)Convert.ToInt32(row["Flags"]);
  1073. entry.Expires = Convert.ToInt32(row["Expires"]);
  1074. return entry;
  1075. }
  1076. /// <summary>
  1077. /// Builds the prim from a datarecord.
  1078. /// </summary>
  1079. /// <param name="primRow">datarecord</param>
  1080. /// <returns></returns>
  1081. private static SceneObjectPart BuildPrim(IDataRecord primRow)
  1082. {
  1083. SceneObjectPart prim = new SceneObjectPart();
  1084. prim.UUID = new UUID((Guid)primRow["UUID"]);
  1085. // explicit conversion of integers is required, which sort
  1086. // of sucks. No idea if there is a shortcut here or not.
  1087. prim.CreationDate = Convert.ToInt32(primRow["CreationDate"]);
  1088. prim.Name = (string)primRow["Name"];
  1089. // various text fields
  1090. prim.Text = (string)primRow["Text"];
  1091. prim.Color = Color.FromArgb(Convert.ToInt32(primRow["ColorA"]),
  1092. Convert.ToInt32(primRow["ColorR"]),
  1093. Convert.ToInt32(primRow["ColorG"]),
  1094. Convert.ToInt32(primRow["ColorB"]));
  1095. prim.Description = (string)primRow["Description"];
  1096. prim.SitName = (string)primRow["SitName"];
  1097. prim.TouchName = (string)primRow["TouchName"];
  1098. // permissions
  1099. prim.Flags = (PrimFlags)Convert.ToUInt32(primRow["ObjectFlags"]);
  1100. //prim.creatorID = new UUID((Guid)primRow["creatorID"]);
  1101. prim.CreatorIdentification = (string)primRow["CreatorID"].ToString();
  1102. prim.OwnerID = new UUID((Guid)primRow["OwnerID"]);
  1103. prim.GroupID = new UUID((Guid)primRow["GroupID"]);
  1104. prim.LastOwnerID = new UUID((Guid)primRow["LastOwnerID"]);
  1105. if (primRow["RezzerID"] != DBNull.Value)
  1106. prim.RezzerID = new UUID((Guid)primRow["RezzerID"]);
  1107. else
  1108. prim.RezzerID = UUID.Zero;
  1109. prim.OwnerMask = Convert.ToUInt32(primRow["OwnerMask"]);
  1110. prim.NextOwnerMask = Convert.ToUInt32(primRow["NextOwnerMask"]);
  1111. prim.GroupMask = Convert.ToUInt32(primRow["GroupMask"]);
  1112. prim.EveryoneMask = Convert.ToUInt32(primRow["EveryoneMask"]);
  1113. prim.BaseMask = Convert.ToUInt32(primRow["BaseMask"]);
  1114. // vectors
  1115. prim.OffsetPosition = new Vector3(
  1116. Convert.ToSingle(primRow["PositionX"]),
  1117. Convert.ToSingle(primRow["PositionY"]),
  1118. Convert.ToSingle(primRow["PositionZ"]));
  1119. prim.GroupPosition = new Vector3(
  1120. Convert.ToSingle(primRow["GroupPositionX"]),
  1121. Convert.ToSingle(primRow["GroupPositionY"]),
  1122. Convert.ToSingle(primRow["GroupPositionZ"]));
  1123. prim.Velocity = new Vector3(
  1124. Convert.ToSingle(primRow["VelocityX"]),
  1125. Convert.ToSingle(primRow["VelocityY"]),
  1126. Convert.ToSingle(primRow["VelocityZ"]));
  1127. prim.AngularVelocity = new Vector3(
  1128. Convert.ToSingle(primRow["AngularVelocityX"]),
  1129. Convert.ToSingle(primRow["AngularVelocityY"]),
  1130. Convert.ToSingle(primRow["AngularVelocityZ"]));
  1131. prim.Acceleration = new Vector3(
  1132. Convert.ToSingle(primRow["AccelerationX"]),
  1133. Convert.ToSingle(primRow["AccelerationY"]),
  1134. Convert.ToSingle(primRow["AccelerationZ"]));
  1135. // quaternions
  1136. prim.RotationOffset = new Quaternion(
  1137. Convert.ToSingle(primRow["RotationX"]),
  1138. Convert.ToSingle(primRow["RotationY"]),
  1139. Convert.ToSingle(primRow["RotationZ"]),
  1140. Convert.ToSingle(primRow["RotationW"]));
  1141. prim.SitTargetPositionLL = new Vector3(
  1142. Convert.ToSingle(primRow["SitTargetOffsetX"]),
  1143. Convert.ToSingle(primRow["SitTargetOffsetY"]),
  1144. Convert.ToSingle(primRow["SitTargetOffsetZ"]));
  1145. prim.SitTargetOrientationLL = new Quaternion(
  1146. Convert.ToSingle(primRow["SitTargetOrientX"]),
  1147. Convert.ToSingle(primRow["SitTargetOrientY"]),
  1148. Convert.ToSingle(primRow["SitTargetOrientZ"]),
  1149. Convert.ToSingle(primRow["SitTargetOrientW"]));
  1150. prim.StandOffset = new Vector3(
  1151. Convert.ToSingle(primRow["standtargetx"]),
  1152. Convert.ToSingle(primRow["standtargety"]),
  1153. Convert.ToSingle(primRow["standtargetz"]));
  1154. prim.SitActiveRange = Convert.ToSingle(primRow["sitactrange"]);
  1155. prim.PayPrice[0] = Convert.ToInt32(primRow["PayPrice"]);
  1156. prim.PayPrice[1] = Convert.ToInt32(primRow["PayButton1"]);
  1157. prim.PayPrice[2] = Convert.ToInt32(primRow["PayButton2"]);
  1158. prim.PayPrice[3] = Convert.ToInt32(primRow["PayButton3"]);
  1159. prim.PayPrice[4] = Convert.ToInt32(primRow["PayButton4"]);
  1160. prim.Sound = new UUID((Guid)primRow["LoopedSound"]);
  1161. prim.SoundGain = Convert.ToSingle(primRow["LoopedSoundGain"]);
  1162. if (prim.Sound.IsZero())
  1163. prim.SoundFlags = 0;
  1164. else
  1165. prim.SoundFlags = 1; // If it's persisted at all, it's looped
  1166. if (!(primRow["TextureAnimation"] is DBNull))
  1167. prim.TextureAnimation = (Byte[])primRow["TextureAnimation"];
  1168. if (!(primRow["ParticleSystem"] is DBNull))
  1169. prim.ParticleSystem = (Byte[])primRow["ParticleSystem"];
  1170. prim.SetCameraEyeOffset(new Vector3(
  1171. Convert.ToSingle(primRow["CameraEyeOffsetX"]),
  1172. Convert.ToSingle(primRow["CameraEyeOffsetY"]),
  1173. Convert.ToSingle(primRow["CameraEyeOffsetZ"])
  1174. ));
  1175. prim.SetCameraAtOffset(new Vector3(
  1176. Convert.ToSingle(primRow["CameraAtOffsetX"]),
  1177. Convert.ToSingle(primRow["CameraAtOffsetY"]),
  1178. Convert.ToSingle(primRow["CameraAtOffsetZ"])
  1179. ));
  1180. if (Convert.ToInt16(primRow["ForceMouselook"]) != 0)
  1181. prim.SetForceMouselook(true);
  1182. prim.ScriptAccessPin = Convert.ToInt32(primRow["ScriptAccessPin"]);
  1183. if (Convert.ToInt16(primRow["AllowedDrop"]) != 0)
  1184. prim.AllowedDrop = true;
  1185. if (Convert.ToInt16(primRow["DieAtEdge"]) != 0)
  1186. prim.DIE_AT_EDGE = true;
  1187. prim.SalePrice = Convert.ToInt32(primRow["SalePrice"]);
  1188. prim.ObjectSaleType = Convert.ToByte(primRow["SaleType"]);
  1189. prim.Material = Convert.ToByte(primRow["Material"]);
  1190. if (!(primRow["ClickAction"] is DBNull))
  1191. prim.ClickAction = Convert.ToByte(primRow["ClickAction"]);
  1192. prim.CollisionSound = new UUID((Guid)primRow["CollisionSound"]);
  1193. prim.CollisionSoundVolume = Convert.ToSingle(primRow["CollisionSoundVolume"]);
  1194. prim.PassTouches = (bool)primRow["PassTouches"];
  1195. prim.PassCollisions = (bool)primRow["PassCollisions"];
  1196. if (!(primRow["MediaURL"] is System.DBNull))
  1197. prim.MediaUrl = (string)primRow["MediaURL"];
  1198. if (!(primRow["DynAttrs"] is System.DBNull) && (string)primRow["DynAttrs"] != "")
  1199. prim.DynAttrs = DAMap.FromXml((string)primRow["DynAttrs"]);
  1200. else
  1201. prim.DynAttrs = null;
  1202. prim.PhysicsShapeType = Convert.ToByte(primRow["PhysicsShapeType"]);
  1203. prim.Density = Convert.ToSingle(primRow["Density"]);
  1204. prim.GravityModifier = Convert.ToSingle(primRow["GravityModifier"]);
  1205. prim.Friction = Convert.ToSingle(primRow["Friction"]);
  1206. prim.Restitution = Convert.ToSingle(primRow["Restitution"]);
  1207. prim.RotationAxisLocks = Convert.ToByte(primRow["RotationAxisLocks"]);
  1208. SOPVehicle vehicle = null;
  1209. if (!(primRow["Vehicle"] is System.DBNull))
  1210. {
  1211. vehicle = SOPVehicle.FromXml2(primRow["Vehicle"].ToString());
  1212. if (vehicle != null)
  1213. prim.VehicleParams = vehicle;
  1214. }
  1215. PhysicsInertiaData pdata = null;
  1216. if (!(primRow["PhysInertia"] is System.DBNull))
  1217. pdata = PhysicsInertiaData.FromXml2(primRow["PhysInertia"].ToString());
  1218. prim.PhysicsInertia = pdata;
  1219. int pseudocrc = Convert.ToInt32(primRow["pseudocrc"]);
  1220. if(pseudocrc != 0)
  1221. prim.PseudoCRC = pseudocrc;
  1222. if (primRow["sopanims"] is not DBNull)
  1223. {
  1224. byte[] data = (byte[])primRow["sopanims"];
  1225. if (data.Length > 0)
  1226. prim.DeSerializeAnimations(data);
  1227. else
  1228. prim.Animations = null;
  1229. }
  1230. else
  1231. {
  1232. prim.Animations = null;
  1233. }
  1234. return prim;
  1235. }
  1236. /// <summary>
  1237. /// Builds the prim shape from a datarecord.
  1238. /// </summary>
  1239. /// <param name="shapeRow">The row.</param>
  1240. /// <returns></returns>
  1241. private static PrimitiveBaseShape BuildShape(IDataRecord shapeRow)
  1242. {
  1243. PrimitiveBaseShape baseShape = new PrimitiveBaseShape();
  1244. baseShape.Scale = new Vector3(
  1245. (float)Convert.ToDouble(shapeRow["ScaleX"]),
  1246. (float)Convert.ToDouble(shapeRow["ScaleY"]),
  1247. (float)Convert.ToDouble(shapeRow["ScaleZ"]));
  1248. // paths
  1249. baseShape.PCode = Convert.ToByte(shapeRow["PCode"]);
  1250. baseShape.PathBegin = Convert.ToUInt16(shapeRow["PathBegin"]);
  1251. baseShape.PathEnd = Convert.ToUInt16(shapeRow["PathEnd"]);
  1252. baseShape.PathScaleX = Convert.ToByte(shapeRow["PathScaleX"]);
  1253. baseShape.PathScaleY = Convert.ToByte(shapeRow["PathScaleY"]);
  1254. baseShape.PathShearX = Convert.ToByte(shapeRow["PathShearX"]);
  1255. baseShape.PathShearY = Convert.ToByte(shapeRow["PathShearY"]);
  1256. baseShape.PathSkew = Convert.ToSByte(shapeRow["PathSkew"]);
  1257. baseShape.PathCurve = Convert.ToByte(shapeRow["PathCurve"]);
  1258. baseShape.PathRadiusOffset = Convert.ToSByte(shapeRow["PathRadiusOffset"]);
  1259. baseShape.PathRevolutions = Convert.ToByte(shapeRow["PathRevolutions"]);
  1260. baseShape.PathTaperX = Convert.ToSByte(shapeRow["PathTaperX"]);
  1261. baseShape.PathTaperY = Convert.ToSByte(shapeRow["PathTaperY"]);
  1262. baseShape.PathTwist = Convert.ToSByte(shapeRow["PathTwist"]);
  1263. baseShape.PathTwistBegin = Convert.ToSByte(shapeRow["PathTwistBegin"]);
  1264. // profile
  1265. baseShape.ProfileBegin = Convert.ToUInt16(shapeRow["ProfileBegin"]);
  1266. baseShape.ProfileEnd = Convert.ToUInt16(shapeRow["ProfileEnd"]);
  1267. baseShape.ProfileCurve = Convert.ToByte(shapeRow["ProfileCurve"]);
  1268. baseShape.ProfileHollow = Convert.ToUInt16(shapeRow["ProfileHollow"]);
  1269. byte[] textureEntry = (byte[])shapeRow["Texture"];
  1270. baseShape.TextureEntry = textureEntry;
  1271. baseShape.ExtraParams = (byte[])shapeRow["ExtraParams"];
  1272. try
  1273. {
  1274. baseShape.State = Convert.ToByte(shapeRow["State"]);
  1275. }
  1276. catch (InvalidCastException)
  1277. {
  1278. }
  1279. if (shapeRow["Media"] is not System.DBNull)
  1280. {
  1281. baseShape.Media = PrimitiveBaseShape.MediaList.FromXml((string)shapeRow["Media"]);
  1282. }
  1283. if (shapeRow["MatOvrd"] is not System.DBNull)
  1284. baseShape.RenderMaterialsOvrFromRawBin((byte[])shapeRow["MatOvrd"]);
  1285. else
  1286. baseShape.RenderMaterialsOvrFromRawBin(null);
  1287. return baseShape;
  1288. }
  1289. /// <summary>
  1290. /// Build a prim inventory item from the persisted data.
  1291. /// </summary>
  1292. /// <param name="inventoryRow"></param>
  1293. /// <returns></returns>
  1294. private static TaskInventoryItem BuildItem(IDataRecord inventoryRow)
  1295. {
  1296. TaskInventoryItem taskItem = new TaskInventoryItem();
  1297. taskItem.ItemID = new UUID((Guid)inventoryRow["itemID"]);
  1298. taskItem.ParentPartID = new UUID((Guid)inventoryRow["primID"]);
  1299. taskItem.AssetID = new UUID((Guid)inventoryRow["assetID"]);
  1300. taskItem.ParentID = new UUID((Guid)inventoryRow["parentFolderID"]);
  1301. taskItem.InvType = Convert.ToInt32(inventoryRow["invType"]);
  1302. taskItem.Type = Convert.ToInt32(inventoryRow["assetType"]);
  1303. taskItem.Name = (string)inventoryRow["name"];
  1304. taskItem.Description = (string)inventoryRow["description"];
  1305. taskItem.CreationDate = Convert.ToUInt32(inventoryRow["creationDate"]);
  1306. //taskItem.creatorID = new UUID((Guid)inventoryRow["creatorID"]);
  1307. taskItem.CreatorIdentification = (string)inventoryRow["creatorID"].ToString();
  1308. taskItem.OwnerID = new UUID((Guid)inventoryRow["ownerID"]);
  1309. taskItem.LastOwnerID = new UUID((Guid)inventoryRow["lastOwnerID"]);
  1310. taskItem.GroupID = new UUID((Guid)inventoryRow["groupID"]);
  1311. taskItem.NextPermissions = Convert.ToUInt32(inventoryRow["nextPermissions"]);
  1312. taskItem.CurrentPermissions = Convert.ToUInt32(inventoryRow["currentPermissions"]);
  1313. taskItem.BasePermissions = Convert.ToUInt32(inventoryRow["basePermissions"]);
  1314. taskItem.EveryonePermissions = Convert.ToUInt32(inventoryRow["everyonePermissions"]);
  1315. taskItem.GroupPermissions = Convert.ToUInt32(inventoryRow["groupPermissions"]);
  1316. taskItem.Flags = Convert.ToUInt32(inventoryRow["flags"]);
  1317. return taskItem;
  1318. }
  1319. #endregion
  1320. #region Create parameters methods
  1321. /// <summary>
  1322. /// Creates the prim inventory parameters.
  1323. /// </summary>
  1324. /// <param name="taskItem">item in inventory.</param>
  1325. /// <returns></returns>
  1326. private NpgsqlParameter[] CreatePrimInventoryParameters(TaskInventoryItem taskItem)
  1327. {
  1328. List<NpgsqlParameter> parameters = new List<NpgsqlParameter>();
  1329. parameters.Add(_Database.CreateParameter("itemID", taskItem.ItemID));
  1330. parameters.Add(_Database.CreateParameter("primID", taskItem.ParentPartID));
  1331. parameters.Add(_Database.CreateParameter("assetID", taskItem.AssetID));
  1332. parameters.Add(_Database.CreateParameter("parentFolderID", taskItem.ParentID));
  1333. parameters.Add(_Database.CreateParameter("invType", taskItem.InvType));
  1334. parameters.Add(_Database.CreateParameter("assetType", taskItem.Type));
  1335. parameters.Add(_Database.CreateParameter("name", taskItem.Name));
  1336. parameters.Add(_Database.CreateParameter("description", taskItem.Description));
  1337. parameters.Add(_Database.CreateParameter("creationDate", taskItem.CreationDate));
  1338. parameters.Add(_Database.CreateParameter("creatorID", taskItem.CreatorID));
  1339. parameters.Add(_Database.CreateParameter("ownerID", taskItem.OwnerID));
  1340. parameters.Add(_Database.CreateParameter("lastOwnerID", taskItem.LastOwnerID));
  1341. parameters.Add(_Database.CreateParameter("groupID", taskItem.GroupID));
  1342. parameters.Add(_Database.CreateParameter("nextPermissions", taskItem.NextPermissions));
  1343. parameters.Add(_Database.CreateParameter("currentPermissions", taskItem.CurrentPermissions));
  1344. parameters.Add(_Database.CreateParameter("basePermissions", taskItem.BasePermissions));
  1345. parameters.Add(_Database.CreateParameter("everyonePermissions", taskItem.EveryonePermissions));
  1346. parameters.Add(_Database.CreateParameter("groupPermissions", taskItem.GroupPermissions));
  1347. parameters.Add(_Database.CreateParameter("flags", taskItem.Flags));
  1348. return parameters.ToArray();
  1349. }
  1350. /// <summary>
  1351. /// Creates the region setting parameters.
  1352. /// </summary>
  1353. /// <param name="settings">regionsettings.</param>
  1354. /// <returns></returns>
  1355. private NpgsqlParameter[] CreateRegionSettingParameters(RegionSettings settings)
  1356. {
  1357. List<NpgsqlParameter> parameters =
  1358. [
  1359. _Database.CreateParameter("regionUUID", settings.RegionUUID),
  1360. _Database.CreateParameter("block_terraform", settings.BlockTerraform),
  1361. _Database.CreateParameter("block_fly", settings.BlockFly),
  1362. _Database.CreateParameter("allow_damage", settings.AllowDamage),
  1363. _Database.CreateParameter("restrict_pushing", settings.RestrictPushing),
  1364. _Database.CreateParameter("allow_land_resell", settings.AllowLandResell),
  1365. _Database.CreateParameter("allow_land_join_divide", settings.AllowLandJoinDivide),
  1366. _Database.CreateParameter("block_show_in_search", settings.BlockShowInSearch),
  1367. _Database.CreateParameter("agent_limit", settings.AgentLimit),
  1368. _Database.CreateParameter("object_bonus", settings.ObjectBonus),
  1369. _Database.CreateParameter("maturity", settings.Maturity),
  1370. _Database.CreateParameter("disable_scripts", settings.DisableScripts),
  1371. _Database.CreateParameter("disable_collisions", settings.DisableCollisions),
  1372. _Database.CreateParameter("disable_physics", settings.DisablePhysics),
  1373. _Database.CreateParameter("terrain_texture_1", settings.TerrainTexture1),
  1374. _Database.CreateParameter("terrain_texture_2", settings.TerrainTexture2),
  1375. _Database.CreateParameter("terrain_texture_3", settings.TerrainTexture3),
  1376. _Database.CreateParameter("terrain_texture_4", settings.TerrainTexture4),
  1377. _Database.CreateParameter("elevation_1_nw", settings.Elevation1NW),
  1378. _Database.CreateParameter("elevation_2_nw", settings.Elevation2NW),
  1379. _Database.CreateParameter("elevation_1_ne", settings.Elevation1NE),
  1380. _Database.CreateParameter("elevation_2_ne", settings.Elevation2NE),
  1381. _Database.CreateParameter("elevation_1_se", settings.Elevation1SE),
  1382. _Database.CreateParameter("elevation_2_se", settings.Elevation2SE),
  1383. _Database.CreateParameter("elevation_1_sw", settings.Elevation1SW),
  1384. _Database.CreateParameter("elevation_2_sw", settings.Elevation2SW),
  1385. _Database.CreateParameter("water_height", settings.WaterHeight),
  1386. _Database.CreateParameter("terrain_raise_limit", settings.TerrainRaiseLimit),
  1387. _Database.CreateParameter("terrain_lower_limit", settings.TerrainLowerLimit),
  1388. _Database.CreateParameter("use_estate_sun", settings.UseEstateSun),
  1389. _Database.CreateParameter("Sandbox", settings.Sandbox),
  1390. _Database.CreateParameter("fixed_sun", settings.FixedSun),
  1391. _Database.CreateParameter("sun_position", settings.SunPosition),
  1392. _Database.CreateParameter("sunvectorx", settings.SunVector.X),
  1393. _Database.CreateParameter("sunvectory", settings.SunVector.Y),
  1394. _Database.CreateParameter("sunvectorz", settings.SunVector.Z),
  1395. _Database.CreateParameter("covenant", settings.Covenant),
  1396. _Database.CreateParameter("covenant_datetime", settings.CovenantChangedDateTime),
  1397. _Database.CreateParameter("Loaded_Creation_DateTime", settings.LoadedCreationDateTime),
  1398. _Database.CreateParameter("Loaded_Creation_ID", settings.LoadedCreationID),
  1399. _Database.CreateParameter("map_tile_ID", settings.TerrainImageID),
  1400. _Database.CreateParameter("block_search", settings.GodBlockSearch),
  1401. _Database.CreateParameter("casino", settings.Casino),
  1402. _Database.CreateParameter("ParcelImageID", settings.ParcelImageID),
  1403. _Database.CreateParameter("TelehubObject", settings.TelehubObject),
  1404. _Database.CreateParameter("cacheID", settings.CacheID),
  1405. _Database.CreateParameter("TerrainPBR1", settings.TerrainPBR1),
  1406. _Database.CreateParameter("TerrainPBR2", settings.TerrainPBR2),
  1407. _Database.CreateParameter("TerrainPBR3", settings.TerrainPBR3),
  1408. _Database.CreateParameter("TerrainPBR4", settings.TerrainPBR4),
  1409. ];
  1410. return parameters.ToArray();
  1411. }
  1412. /// <summary>
  1413. /// Creates the land parameters.
  1414. /// </summary>
  1415. /// <param name="land">land parameters.</param>
  1416. /// <param name="regionUUID">region UUID.</param>
  1417. /// <returns></returns>
  1418. private NpgsqlParameter[] CreateLandParameters(LandData land, UUID regionUUID)
  1419. {
  1420. List<NpgsqlParameter> parameters = new List<NpgsqlParameter>();
  1421. parameters.Add(_Database.CreateParameter("UUID", land.GlobalID));
  1422. parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID));
  1423. parameters.Add(_Database.CreateParameter("LocalLandID", land.LocalID));
  1424. // Bitmap is a byte[512]
  1425. parameters.Add(_Database.CreateParameter("Bitmap", land.Bitmap));
  1426. parameters.Add(_Database.CreateParameter("Name", land.Name));
  1427. parameters.Add(_Database.CreateParameter("Description", land.Description));
  1428. parameters.Add(_Database.CreateParameter("OwnerUUID", land.OwnerID));
  1429. parameters.Add(_Database.CreateParameter("IsGroupOwned", land.IsGroupOwned));
  1430. parameters.Add(_Database.CreateParameter("Area", land.Area));
  1431. parameters.Add(_Database.CreateParameter("AuctionID", land.AuctionID)); //Unemplemented
  1432. parameters.Add(_Database.CreateParameter("Category", (int)land.Category)); //Enum libsecondlife.Parcel.ParcelCategory
  1433. parameters.Add(_Database.CreateParameter("ClaimDate", land.ClaimDate));
  1434. parameters.Add(_Database.CreateParameter("ClaimPrice", land.ClaimPrice));
  1435. parameters.Add(_Database.CreateParameter("GroupUUID", land.GroupID));
  1436. parameters.Add(_Database.CreateParameter("SalePrice", land.SalePrice));
  1437. parameters.Add(_Database.CreateParameter("LandStatus", (int)land.Status)); //Enum. libsecondlife.Parcel.ParcelStatus
  1438. parameters.Add(_Database.CreateParameter("LandFlags", land.Flags));
  1439. parameters.Add(_Database.CreateParameter("LandingType", Convert.ToInt32( land.LandingType) ));
  1440. parameters.Add(_Database.CreateParameter("MediaAutoScale", Convert.ToInt32( land.MediaAutoScale )));
  1441. parameters.Add(_Database.CreateParameter("MediaTextureUUID", land.MediaID));
  1442. parameters.Add(_Database.CreateParameter("MediaURL", land.MediaURL));
  1443. parameters.Add(_Database.CreateParameter("MusicURL", land.MusicURL));
  1444. parameters.Add(_Database.CreateParameter("PassHours", land.PassHours));
  1445. parameters.Add(_Database.CreateParameter("PassPrice", land.PassPrice));
  1446. parameters.Add(_Database.CreateParameter("SnapshotUUID", land.SnapshotID));
  1447. parameters.Add(_Database.CreateParameter("UserLocationX", land.UserLocation.X));
  1448. parameters.Add(_Database.CreateParameter("UserLocationY", land.UserLocation.Y));
  1449. parameters.Add(_Database.CreateParameter("UserLocationZ", land.UserLocation.Z));
  1450. parameters.Add(_Database.CreateParameter("UserLookAtX", land.UserLookAt.X));
  1451. parameters.Add(_Database.CreateParameter("UserLookAtY", land.UserLookAt.Y));
  1452. parameters.Add(_Database.CreateParameter("UserLookAtZ", land.UserLookAt.Z));
  1453. parameters.Add(_Database.CreateParameter("AuthBuyerID", land.AuthBuyerID));
  1454. parameters.Add(_Database.CreateParameter("OtherCleanTime", land.OtherCleanTime));
  1455. parameters.Add(_Database.CreateParameter("Dwell", land.Dwell));
  1456. parameters.Add(_Database.CreateParameter("MediaDescription", land.MediaDescription));
  1457. parameters.Add(_Database.CreateParameter("MediaType", land.MediaType));
  1458. parameters.Add(_Database.CreateParameter("MediaWidth", land.MediaWidth));
  1459. parameters.Add(_Database.CreateParameter("MediaHeight", land.MediaHeight));
  1460. parameters.Add(_Database.CreateParameter("MediaLoop", land.MediaLoop));
  1461. parameters.Add(_Database.CreateParameter("ObscureMusic", land.ObscureMusic));
  1462. parameters.Add(_Database.CreateParameter("ObscureMedia", land.ObscureMedia));
  1463. parameters.Add(_Database.CreateParameter("SeeAVs", land.SeeAVs));
  1464. parameters.Add(_Database.CreateParameter("AnyAVSounds", land.AnyAVSounds));
  1465. parameters.Add(_Database.CreateParameter("GroupAVSounds", land.GroupAVSounds));
  1466. if (land.Environment == null)
  1467. parameters.Add(_Database.CreateParameter("environment", ""));
  1468. else
  1469. {
  1470. try
  1471. {
  1472. parameters.Add(_Database.CreateParameter("environment", ViewerEnvironment.ToOSDString(land.Environment)));
  1473. }
  1474. catch
  1475. {
  1476. parameters.Add(_Database.CreateParameter("environment", ""));
  1477. }
  1478. }
  1479. return parameters.ToArray();
  1480. }
  1481. /// <summary>
  1482. /// Creates the land access parameters.
  1483. /// </summary>
  1484. /// <param name="parcelAccessEntry">parcel access entry.</param>
  1485. /// <param name="parcelID">parcel ID.</param>
  1486. /// <returns></returns>
  1487. private NpgsqlParameter[] CreateLandAccessParameters(LandAccessEntry parcelAccessEntry, UUID parcelID)
  1488. {
  1489. List<NpgsqlParameter> parameters = new List<NpgsqlParameter>();
  1490. parameters.Add(_Database.CreateParameter("LandUUID", parcelID));
  1491. parameters.Add(_Database.CreateParameter("AccessUUID", parcelAccessEntry.AgentID));
  1492. parameters.Add(_Database.CreateParameter("Flags", parcelAccessEntry.Flags));
  1493. parameters.Add(_Database.CreateParameter("Expires", parcelAccessEntry.Expires));
  1494. return parameters.ToArray();
  1495. }
  1496. /// <summary>
  1497. /// Creates the prim parameters for storing in DB.
  1498. /// </summary>
  1499. /// <param name="prim">Basic data of SceneObjectpart prim.</param>
  1500. /// <param name="sceneGroupID">The scenegroup ID.</param>
  1501. /// <param name="regionUUID">The region ID.</param>
  1502. /// <returns></returns>
  1503. private NpgsqlParameter[] CreatePrimParameters(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)
  1504. {
  1505. List<NpgsqlParameter> parameters = new List<NpgsqlParameter>();
  1506. parameters.Add(_Database.CreateParameter("UUID", prim.UUID));
  1507. parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID));
  1508. parameters.Add(_Database.CreateParameter("CreationDate", prim.CreationDate));
  1509. parameters.Add(_Database.CreateParameter("Name", prim.Name));
  1510. parameters.Add(_Database.CreateParameter("SceneGroupID", sceneGroupID));
  1511. // the UUID of the root part for this SceneObjectGroup
  1512. // various text fields
  1513. parameters.Add(_Database.CreateParameter("Text", prim.Text));
  1514. parameters.Add(_Database.CreateParameter("ColorR", prim.Color.R));
  1515. parameters.Add(_Database.CreateParameter("ColorG", prim.Color.G));
  1516. parameters.Add(_Database.CreateParameter("ColorB", prim.Color.B));
  1517. parameters.Add(_Database.CreateParameter("ColorA", prim.Color.A));
  1518. parameters.Add(_Database.CreateParameter("Description", prim.Description));
  1519. parameters.Add(_Database.CreateParameter("SitName", prim.SitName));
  1520. parameters.Add(_Database.CreateParameter("TouchName", prim.TouchName));
  1521. // permissions
  1522. parameters.Add(_Database.CreateParameter("ObjectFlags", (uint)prim.Flags));
  1523. parameters.Add(_Database.CreateParameter("CreatorID", prim.CreatorID));
  1524. parameters.Add(_Database.CreateParameter("OwnerID", prim.OwnerID));
  1525. parameters.Add(_Database.CreateParameter("GroupID", prim.GroupID));
  1526. parameters.Add(_Database.CreateParameter("LastOwnerID", prim.LastOwnerID));
  1527. parameters.Add(_Database.CreateParameter("RezzerID", prim.RezzerID));
  1528. parameters.Add(_Database.CreateParameter("OwnerMask", prim.OwnerMask));
  1529. parameters.Add(_Database.CreateParameter("NextOwnerMask", prim.NextOwnerMask));
  1530. parameters.Add(_Database.CreateParameter("GroupMask", prim.GroupMask));
  1531. parameters.Add(_Database.CreateParameter("EveryoneMask", prim.EveryoneMask));
  1532. parameters.Add(_Database.CreateParameter("BaseMask", prim.BaseMask));
  1533. // vectors
  1534. parameters.Add(_Database.CreateParameter("PositionX", prim.OffsetPosition.X));
  1535. parameters.Add(_Database.CreateParameter("PositionY", prim.OffsetPosition.Y));
  1536. parameters.Add(_Database.CreateParameter("PositionZ", prim.OffsetPosition.Z));
  1537. parameters.Add(_Database.CreateParameter("GroupPositionX", prim.GroupPosition.X));
  1538. parameters.Add(_Database.CreateParameter("GroupPositionY", prim.GroupPosition.Y));
  1539. parameters.Add(_Database.CreateParameter("GroupPositionZ", prim.GroupPosition.Z));
  1540. parameters.Add(_Database.CreateParameter("VelocityX", prim.Velocity.X));
  1541. parameters.Add(_Database.CreateParameter("VelocityY", prim.Velocity.Y));
  1542. parameters.Add(_Database.CreateParameter("VelocityZ", prim.Velocity.Z));
  1543. parameters.Add(_Database.CreateParameter("AngularVelocityX", prim.AngularVelocity.X));
  1544. parameters.Add(_Database.CreateParameter("AngularVelocityY", prim.AngularVelocity.Y));
  1545. parameters.Add(_Database.CreateParameter("AngularVelocityZ", prim.AngularVelocity.Z));
  1546. parameters.Add(_Database.CreateParameter("AccelerationX", prim.Acceleration.X));
  1547. parameters.Add(_Database.CreateParameter("AccelerationY", prim.Acceleration.Y));
  1548. parameters.Add(_Database.CreateParameter("AccelerationZ", prim.Acceleration.Z));
  1549. // quaternions
  1550. parameters.Add(_Database.CreateParameter("RotationX", prim.RotationOffset.X));
  1551. parameters.Add(_Database.CreateParameter("RotationY", prim.RotationOffset.Y));
  1552. parameters.Add(_Database.CreateParameter("RotationZ", prim.RotationOffset.Z));
  1553. parameters.Add(_Database.CreateParameter("RotationW", prim.RotationOffset.W));
  1554. // Sit target
  1555. Vector3 sitTargetPos = prim.SitTargetPositionLL;
  1556. parameters.Add(_Database.CreateParameter("SitTargetOffsetX", sitTargetPos.X));
  1557. parameters.Add(_Database.CreateParameter("SitTargetOffsetY", sitTargetPos.Y));
  1558. parameters.Add(_Database.CreateParameter("SitTargetOffsetZ", sitTargetPos.Z));
  1559. Quaternion sitTargetOrient = prim.SitTargetOrientationLL;
  1560. parameters.Add(_Database.CreateParameter("SitTargetOrientW", sitTargetOrient.W));
  1561. parameters.Add(_Database.CreateParameter("SitTargetOrientX", sitTargetOrient.X));
  1562. parameters.Add(_Database.CreateParameter("SitTargetOrientY", sitTargetOrient.Y));
  1563. parameters.Add(_Database.CreateParameter("SitTargetOrientZ", sitTargetOrient.Z));
  1564. Vector3 standTargetPos = prim.StandOffset;
  1565. parameters.Add(_Database.CreateParameter("standtargetx", standTargetPos.X));
  1566. parameters.Add(_Database.CreateParameter("standtargety", standTargetPos.Y));
  1567. parameters.Add(_Database.CreateParameter("standtargetz", standTargetPos.Z));
  1568. parameters.Add(_Database.CreateParameter("sitactrange", prim.SitActiveRange));
  1569. parameters.Add(_Database.CreateParameter("PayPrice", prim.PayPrice[0]));
  1570. parameters.Add(_Database.CreateParameter("PayButton1", prim.PayPrice[1]));
  1571. parameters.Add(_Database.CreateParameter("PayButton2", prim.PayPrice[2]));
  1572. parameters.Add(_Database.CreateParameter("PayButton3", prim.PayPrice[3]));
  1573. parameters.Add(_Database.CreateParameter("PayButton4", prim.PayPrice[4]));
  1574. if ((prim.SoundFlags & 1) != 0) // Looped
  1575. {
  1576. parameters.Add(_Database.CreateParameter("LoopedSound", prim.Sound));
  1577. parameters.Add(_Database.CreateParameter("LoopedSoundGain", prim.SoundGain));
  1578. }
  1579. else
  1580. {
  1581. parameters.Add(_Database.CreateParameter("LoopedSound", UUID.Zero));
  1582. parameters.Add(_Database.CreateParameter("LoopedSoundGain", 0.0f));
  1583. }
  1584. parameters.Add(_Database.CreateParameter("TextureAnimation", prim.TextureAnimation));
  1585. parameters.Add(_Database.CreateParameter("ParticleSystem", prim.ParticleSystem));
  1586. parameters.Add(_Database.CreateParameter("CameraEyeOffsetX", prim.GetCameraEyeOffset().X));
  1587. parameters.Add(_Database.CreateParameter("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y));
  1588. parameters.Add(_Database.CreateParameter("CameraEyeOffsetZ", prim.GetCameraEyeOffset().Z));
  1589. parameters.Add(_Database.CreateParameter("CameraAtOffsetX", prim.GetCameraAtOffset().X));
  1590. parameters.Add(_Database.CreateParameter("CameraAtOffsetY", prim.GetCameraAtOffset().Y));
  1591. parameters.Add(_Database.CreateParameter("CameraAtOffsetZ", prim.GetCameraAtOffset().Z));
  1592. if (prim.GetForceMouselook())
  1593. parameters.Add(_Database.CreateParameter("ForceMouselook", 1));
  1594. else
  1595. parameters.Add(_Database.CreateParameter("ForceMouselook", 0));
  1596. parameters.Add(_Database.CreateParameter("ScriptAccessPin", prim.ScriptAccessPin));
  1597. if (prim.AllowedDrop)
  1598. parameters.Add(_Database.CreateParameter("AllowedDrop", 1));
  1599. else
  1600. parameters.Add(_Database.CreateParameter("AllowedDrop", 0));
  1601. if (prim.DIE_AT_EDGE)
  1602. parameters.Add(_Database.CreateParameter("DieAtEdge", 1));
  1603. else
  1604. parameters.Add(_Database.CreateParameter("DieAtEdge", 0));
  1605. parameters.Add(_Database.CreateParameter("SalePrice", prim.SalePrice));
  1606. parameters.Add(_Database.CreateParameter("SaleType", prim.ObjectSaleType));
  1607. byte clickAction = prim.ClickAction;
  1608. parameters.Add(_Database.CreateParameter("ClickAction", clickAction));
  1609. parameters.Add(_Database.CreateParameter("Material", prim.Material));
  1610. parameters.Add(_Database.CreateParameter("CollisionSound", prim.CollisionSound));
  1611. parameters.Add(_Database.CreateParameter("CollisionSoundVolume", prim.CollisionSoundVolume));
  1612. parameters.Add(_Database.CreateParameter("PassTouches", (bool)prim.PassTouches));
  1613. parameters.Add(_Database.CreateParameter("PassCollisions", (bool)prim.PassCollisions));
  1614. if (prim.PassTouches)
  1615. parameters.Add(_Database.CreateParameter("PassTouches", true));
  1616. else
  1617. parameters.Add(_Database.CreateParameter("PassTouches", false));
  1618. if (prim.PassCollisions)
  1619. parameters.Add(_Database.CreateParameter("PassCollisions", true));
  1620. else
  1621. parameters.Add(_Database.CreateParameter("PassCollisions", false));
  1622. parameters.Add(_Database.CreateParameter("LinkNumber", prim.LinkNum));
  1623. parameters.Add(_Database.CreateParameter("MediaURL", prim.MediaUrl));
  1624. if (prim.VehicleParams != null)
  1625. parameters.Add(_Database.CreateParameter("Vehicle", prim.VehicleParams.ToXml2()));
  1626. else
  1627. parameters.Add(_Database.CreateParameter("Vehicle", string.Empty));
  1628. if (prim.PhysicsInertia != null)
  1629. parameters.Add(_Database.CreateParameter("PhysInertia", prim.PhysicsInertia.ToXml2()));
  1630. else
  1631. parameters.Add(_Database.CreateParameter("PhysInertia", string.Empty));
  1632. if (prim.DynAttrs != null && prim.DynAttrs.CountNamespaces > 0)
  1633. parameters.Add(_Database.CreateParameter("DynAttrs", prim.DynAttrs.ToXml()));
  1634. else
  1635. parameters.Add(_Database.CreateParameter("DynAttrs", null));
  1636. parameters.Add(_Database.CreateParameter("PhysicsShapeType", prim.PhysicsShapeType));
  1637. parameters.Add(_Database.CreateParameter("Density", (double)prim.Density));
  1638. parameters.Add(_Database.CreateParameter("GravityModifier", (double)prim.GravityModifier));
  1639. parameters.Add(_Database.CreateParameter("Friction", (double)prim.Friction));
  1640. parameters.Add(_Database.CreateParameter("Restitution", (double)prim.Restitution));
  1641. parameters.Add(_Database.CreateParameter("RotationAxisLocks", prim.RotationAxisLocks));
  1642. parameters.Add(_Database.CreateParameter("pseudocrc", prim.PseudoCRC));
  1643. if (prim.Animations != null)
  1644. parameters.Add(_Database.CreateParameter("sopanims", prim.SerializeAnimations()));
  1645. else
  1646. parameters.Add(_Database.CreateParameterNullBytea("sopanims"));
  1647. if (prim.IsRoot && prim.ParentGroup.LinksetData is not null)
  1648. parameters.Add(_Database.CreateParameter("lnkstBinData", prim.ParentGroup.LinksetData.ToBin()));
  1649. else
  1650. parameters.Add(_Database.CreateParameterNullBytea("lnkstBinData"));
  1651. return parameters.ToArray();
  1652. }
  1653. /// <summary>
  1654. /// Creates the primshape parameters for storing in DB.
  1655. /// </summary>
  1656. /// <param name="prim">Basic data of SceneObjectpart prim.</param>
  1657. /// <param name="sceneGroupID">The scene group ID.</param>
  1658. /// <param name="regionUUID">The region UUID.</param>
  1659. /// <returns></returns>
  1660. private NpgsqlParameter[] CreatePrimShapeParameters(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)
  1661. {
  1662. List<NpgsqlParameter> parameters = new List<NpgsqlParameter>();
  1663. PrimitiveBaseShape s = prim.Shape;
  1664. parameters.Add(_Database.CreateParameter("UUID", prim.UUID));
  1665. // shape is an enum
  1666. parameters.Add(_Database.CreateParameter("Shape", 0));
  1667. // vectors
  1668. parameters.Add(_Database.CreateParameter("ScaleX", s.Scale.X));
  1669. parameters.Add(_Database.CreateParameter("ScaleY", s.Scale.Y));
  1670. parameters.Add(_Database.CreateParameter("ScaleZ", s.Scale.Z));
  1671. // paths
  1672. parameters.Add(_Database.CreateParameter("PCode", s.PCode));
  1673. parameters.Add(_Database.CreateParameter("PathBegin", s.PathBegin));
  1674. parameters.Add(_Database.CreateParameter("PathEnd", s.PathEnd));
  1675. parameters.Add(_Database.CreateParameter("PathScaleX", s.PathScaleX));
  1676. parameters.Add(_Database.CreateParameter("PathScaleY", s.PathScaleY));
  1677. parameters.Add(_Database.CreateParameter("PathShearX", s.PathShearX));
  1678. parameters.Add(_Database.CreateParameter("PathShearY", s.PathShearY));
  1679. parameters.Add(_Database.CreateParameter("PathSkew", s.PathSkew));
  1680. parameters.Add(_Database.CreateParameter("PathCurve", s.PathCurve));
  1681. parameters.Add(_Database.CreateParameter("PathRadiusOffset", s.PathRadiusOffset));
  1682. parameters.Add(_Database.CreateParameter("PathRevolutions", s.PathRevolutions));
  1683. parameters.Add(_Database.CreateParameter("PathTaperX", s.PathTaperX));
  1684. parameters.Add(_Database.CreateParameter("PathTaperY", s.PathTaperY));
  1685. parameters.Add(_Database.CreateParameter("PathTwist", s.PathTwist));
  1686. parameters.Add(_Database.CreateParameter("PathTwistBegin", s.PathTwistBegin));
  1687. // profile
  1688. parameters.Add(_Database.CreateParameter("ProfileBegin", s.ProfileBegin));
  1689. parameters.Add(_Database.CreateParameter("ProfileEnd", s.ProfileEnd));
  1690. parameters.Add(_Database.CreateParameter("ProfileCurve", s.ProfileCurve));
  1691. parameters.Add(_Database.CreateParameter("ProfileHollow", s.ProfileHollow));
  1692. if (s.TextureEntry is null)
  1693. parameters.Add(_Database.CreateParameterNullBytea("Texture"));
  1694. else
  1695. parameters.Add(_Database.CreateParameter("Texture", s.TextureEntry));
  1696. if (s.ExtraParams is null)
  1697. parameters.Add(_Database.CreateParameterNullBytea("ExtraParams"));
  1698. else
  1699. parameters.Add(_Database.CreateParameter("ExtraParams", s.ExtraParams));
  1700. parameters.Add(_Database.CreateParameter("State", s.State));
  1701. if (null == s.Media)
  1702. {
  1703. parameters.Add(_Database.CreateParameter("Media", DBNull.Value));
  1704. }
  1705. else
  1706. {
  1707. parameters.Add(_Database.CreateParameter("Media", s.Media.ToXml()));
  1708. }
  1709. byte[] matovrdata = s.RenderMaterialsOvrToRawBin();
  1710. if(matovrdata is null)
  1711. parameters.Add(_Database.CreateParameterNullBytea("MatOvrd"));
  1712. else
  1713. parameters.Add(_Database.CreateParameter("MatOvrd", matovrdata));
  1714. return parameters.ToArray();
  1715. }
  1716. #endregion
  1717. private void LoadSpawnPoints(RegionSettings rs)
  1718. {
  1719. rs.ClearSpawnPoints();
  1720. string sql = @"SELECT ""Yaw"", ""Pitch"", ""Distance"" FROM spawn_points WHERE ""RegionUUID"" = :RegionUUID";
  1721. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  1722. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  1723. {
  1724. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", rs.RegionUUID));
  1725. conn.Open();
  1726. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  1727. {
  1728. while (reader.Read())
  1729. {
  1730. var sp = new SpawnPoint
  1731. {
  1732. Yaw = Convert.ToSingle(reader["Yaw"]),
  1733. Pitch = Convert.ToSingle(reader["Pitch"]),
  1734. Distance = Convert.ToSingle(reader["Distance"])
  1735. };
  1736. rs.AddSpawnPoint(sp);
  1737. }
  1738. }
  1739. }
  1740. }
  1741. private void SaveSpawnPoints(RegionSettings rs)
  1742. {
  1743. string sql = @"DELETE FROM spawn_points WHERE ""RegionUUID"" = :RegionUUID";
  1744. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  1745. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  1746. {
  1747. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", rs.RegionUUID));
  1748. conn.Open();
  1749. cmd.ExecuteNonQuery();
  1750. }
  1751. foreach (SpawnPoint p in rs.SpawnPoints())
  1752. {
  1753. sql = @"INSERT INTO spawn_points (""RegionUUID"", ""Yaw"", ""Pitch"", ""Distance"") VALUES (:RegionUUID, :Yaw, :Pitch, :Distance)";
  1754. using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
  1755. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  1756. {
  1757. cmd.Parameters.Add(_Database.CreateParameter("RegionUUID", rs.RegionUUID));
  1758. cmd.Parameters.Add(_Database.CreateParameter("Yaw", p.Yaw));
  1759. cmd.Parameters.Add(_Database.CreateParameter("Pitch", p.Pitch));
  1760. cmd.Parameters.Add(_Database.CreateParameter("Distance", p.Distance));
  1761. conn.Open();
  1762. cmd.ExecuteNonQuery();
  1763. }
  1764. }
  1765. }
  1766. public UUID[] GetObjectIDs(UUID regionID)
  1767. {
  1768. return new UUID[0];
  1769. }
  1770. public void SaveExtra(UUID regionID, string name, string value)
  1771. {
  1772. const string queryString = """
  1773. INSERT INTO regionextra ("RegionID", "Name", "value")
  1774. VALUES (:RegionID, :Name, :Value)
  1775. """;
  1776. using var connection = new NpgsqlConnection(m_connectionString);
  1777. connection.Open();
  1778. using var command = new NpgsqlCommand(queryString, connection, connection.BeginTransaction());
  1779. try
  1780. {
  1781. command.Parameters.AddWithValue("RegionID", regionID.ToString());
  1782. command.Parameters.AddWithValue("Name", name);
  1783. command.Parameters.AddWithValue("Value", value);
  1784. command.ExecuteNonQuery();
  1785. command.Transaction.Commit();
  1786. }
  1787. catch (Exception e)
  1788. {
  1789. Console.WriteLine(e);
  1790. command.Transaction.Rollback();
  1791. }
  1792. }
  1793. public void RemoveExtra(UUID regionID, string name)
  1794. {
  1795. const string queryString = """DELETE FROM regionextra WHERE "RegionID"=:RegionID AND "Name"=:Name""";
  1796. using var connection = new NpgsqlConnection(m_connectionString);
  1797. connection.Open();
  1798. using var command = new NpgsqlCommand(queryString, connection, connection.BeginTransaction());
  1799. try
  1800. {
  1801. command.Parameters.AddWithValue("RegionID", regionID.ToString());
  1802. command.Parameters.AddWithValue("Name", name);
  1803. command.ExecuteNonQuery();
  1804. command.Transaction.Commit();
  1805. }
  1806. catch (Exception e)
  1807. {
  1808. Console.WriteLine(e);
  1809. command.Transaction.Rollback();
  1810. }
  1811. }
  1812. public Dictionary<string, string> GetExtra(UUID regionID)
  1813. {
  1814. const string queryString = """SELECT * FROM regionextra WHERE "RegionID" = :RegionID""";
  1815. using NpgsqlConnection conn = new NpgsqlConnection(m_connectionString);
  1816. using NpgsqlCommand cmd = new NpgsqlCommand(queryString, conn);
  1817. cmd.Parameters.Add(_Database.CreateParameter("RegionID", regionID.ToString()));
  1818. conn.Open();
  1819. using NpgsqlDataReader reader = cmd.ExecuteReader();
  1820. Dictionary<string, string> extraSettings = new Dictionary<string, string>();
  1821. while (reader.Read())
  1822. {
  1823. extraSettings.Add(reader["Name"].ToString(), reader["value"].ToString());
  1824. }
  1825. return extraSettings;
  1826. }
  1827. }
  1828. }