ArchiveReadRequest.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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.IO;
  30. using System.IO.Compression;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Monitoring;
  39. using OpenSim.Framework.Serialization;
  40. using OpenSim.Framework.Serialization.External;
  41. using OpenSim.Region.CoreModules.World.Terrain;
  42. using OpenSim.Region.CoreModules.World.Land;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Scenes.Serialization;
  46. using OpenSim.Services.Interfaces;
  47. using System.Threading;
  48. namespace OpenSim.Region.CoreModules.World.Archiver
  49. {
  50. /// <summary>
  51. /// Handles an individual archive read request
  52. /// </summary>
  53. public class ArchiveReadRequest
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. /// <summary>
  57. /// Contains data used while dearchiving a single scene.
  58. /// </summary>
  59. private class DearchiveContext
  60. {
  61. public Scene Scene { get; set; }
  62. public List<string> SerialisedSceneObjects { get; set; }
  63. public List<string> SerialisedParcels { get; set; }
  64. public List<SceneObjectGroup> SceneObjects { get; set; }
  65. public DearchiveContext(Scene scene)
  66. {
  67. Scene = scene;
  68. SerialisedSceneObjects = new List<string>();
  69. SerialisedParcels = new List<string>();
  70. SceneObjects = new List<SceneObjectGroup>();
  71. }
  72. }
  73. /// <summary>
  74. /// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version
  75. /// bumps here should be compatible.
  76. /// </summary>
  77. public static int MAX_MAJOR_VERSION = 1;
  78. /// <summary>
  79. /// Has the control file been loaded for this archive?
  80. /// </summary>
  81. public bool ControlFileLoaded { get; private set; }
  82. protected string m_loadPath;
  83. protected Scene m_rootScene;
  84. protected Stream m_loadStream;
  85. protected Guid m_requestId;
  86. protected string m_errorMessage;
  87. /// <value>
  88. /// Should the archive being loaded be merged with what is already on the region?
  89. /// Merging usually suppresses terrain and parcel loading
  90. /// </value>
  91. protected bool m_merge;
  92. protected bool m_mergeReplaceObjects;
  93. /// <value>
  94. /// If true, force the loading of terrain from the oar file
  95. /// </value>
  96. protected bool m_mergeTerrain;
  97. /// <value>
  98. /// If true, force the merge of parcels from the oar file
  99. /// </value>
  100. protected bool m_mergeParcels;
  101. /// <value>
  102. /// Should we ignore any assets when reloading the archive?
  103. /// </value>
  104. protected bool m_skipAssets;
  105. /// <value>
  106. /// Displacement added to each object as it is added to the world
  107. /// </value>
  108. protected Vector3 m_displacement = Vector3.Zero;
  109. /// <value>
  110. /// Rotation (in radians) to apply to the objects as they are loaded.
  111. /// </value>
  112. protected float m_rotation = 0f;
  113. /// <value>
  114. /// original oar region size. not using Constants.RegionSize
  115. /// </value>
  116. protected Vector3 m_incomingRegionSize = new Vector3(256f, 256f, float.MaxValue);
  117. /// <value>
  118. /// Center around which to apply the rotation relative to the original oar position
  119. /// </value>
  120. protected Vector3 m_rotationCenter = new Vector3(128f, 128f, 0f);
  121. /// <value>
  122. /// Corner 1 of a bounding cuboid which specifies which objects we load from the oar
  123. /// </value>
  124. protected Vector3 m_boundingOrigin = Vector3.Zero;
  125. /// <value>
  126. /// Size of a bounding cuboid which specifies which objects we load from the oar
  127. /// </value>
  128. protected Vector3 m_boundingSize = new Vector3(Constants.MaximumRegionSize, Constants.MaximumRegionSize, float.MaxValue);
  129. protected bool m_noObjects = false;
  130. protected bool m_boundingBox = false;
  131. protected bool m_debug = false;
  132. /// <summary>
  133. /// Used to cache lookups for valid uuids.
  134. /// </summary>
  135. private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
  136. private IUserManagement m_UserMan;
  137. private IUserManagement UserManager
  138. {
  139. get
  140. {
  141. if (m_UserMan == null)
  142. {
  143. m_UserMan = m_rootScene.RequestModuleInterface<IUserManagement>();
  144. }
  145. return m_UserMan;
  146. }
  147. }
  148. /// <summary>
  149. /// Used to cache lookups for valid groups.
  150. /// </summary>
  151. private IDictionary<UUID, bool> m_validGroupUuids = new Dictionary<UUID, bool>();
  152. private IGroupsModule m_groupsModule;
  153. private IAssetService m_assetService = null;
  154. private UUID m_defaultUser;
  155. public ArchiveReadRequest(Scene scene, string loadPath, Guid requestId, Dictionary<string, object> options)
  156. {
  157. m_rootScene = scene;
  158. if (options.ContainsKey("default-user"))
  159. {
  160. m_defaultUser = (UUID)options["default-user"];
  161. m_log.InfoFormat("Using User {0} as default user", m_defaultUser.ToString());
  162. }
  163. else
  164. {
  165. m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
  166. }
  167. m_loadPath = loadPath;
  168. try
  169. {
  170. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
  171. }
  172. catch (EntryPointNotFoundException e)
  173. {
  174. m_log.ErrorFormat(
  175. "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
  176. + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
  177. m_log.Error(e);
  178. }
  179. m_errorMessage = String.Empty;
  180. m_merge = options.ContainsKey("merge");
  181. m_mergeReplaceObjects = options.ContainsKey("mReplaceObjects");
  182. m_mergeTerrain = options.ContainsKey("merge-terrain");
  183. m_mergeParcels = options.ContainsKey("merge-parcels");
  184. m_noObjects = options.ContainsKey("no-objects");
  185. m_skipAssets = options.ContainsKey("skipAssets");
  186. m_requestId = requestId;
  187. m_displacement = options.ContainsKey("displacement") ? (Vector3)options["displacement"] : Vector3.Zero;
  188. m_rotation = options.ContainsKey("rotation") ? (float)options["rotation"] : 0f;
  189. m_boundingOrigin = Vector3.Zero;
  190. m_boundingSize = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, float.MaxValue);
  191. if (options.ContainsKey("bounding-origin"))
  192. {
  193. Vector3 boOption = (Vector3)options["bounding-origin"];
  194. if (boOption != m_boundingOrigin)
  195. {
  196. m_boundingOrigin = boOption;
  197. }
  198. m_boundingBox = true;
  199. }
  200. if (options.ContainsKey("bounding-size"))
  201. {
  202. Vector3 bsOption = (Vector3)options["bounding-size"];
  203. bool clip = false;
  204. if (bsOption.X <= 0 || bsOption.X > m_boundingSize.X)
  205. {
  206. bsOption.X = m_boundingSize.X;
  207. clip = true;
  208. }
  209. if (bsOption.Y <= 0 || bsOption.Y > m_boundingSize.Y)
  210. {
  211. bsOption.Y = m_boundingSize.Y;
  212. clip = true;
  213. }
  214. if (bsOption != m_boundingSize)
  215. {
  216. m_boundingSize = bsOption;
  217. m_boundingBox = true;
  218. }
  219. if (clip) m_log.InfoFormat("[ARCHIVER]: The bounding cube specified is larger than the destination region! Clipping to {0}.", m_boundingSize.ToString());
  220. }
  221. m_debug = options.ContainsKey("debug");
  222. // Zero can never be a valid user id (or group)
  223. m_validUserUuids[UUID.Zero] = false;
  224. m_validGroupUuids[UUID.Zero] = false;
  225. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  226. m_assetService = m_rootScene.AssetService;
  227. }
  228. public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object> options)
  229. {
  230. m_rootScene = scene;
  231. m_loadPath = null;
  232. m_loadStream = loadStream;
  233. m_skipAssets = options.ContainsKey("skipAssets");
  234. m_merge = options.ContainsKey("merge");
  235. m_mergeReplaceObjects = options.ContainsKey("mReplaceObjects");
  236. m_requestId = requestId;
  237. m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
  238. // Zero can never be a valid user id
  239. m_validUserUuids[UUID.Zero] = false;
  240. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  241. m_assetService = m_rootScene.AssetService;
  242. }
  243. /// <summary>
  244. /// Dearchive the region embodied in this request.
  245. /// </summary>
  246. public void DearchiveRegion()
  247. {
  248. DearchiveRegion(true);
  249. }
  250. public void DearchiveRegion(bool shouldStartScripts)
  251. {
  252. int successfulAssetRestores = 0;
  253. int failedAssetRestores = 0;
  254. DearchiveScenesInfo dearchivedScenes;
  255. // We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
  256. // Therefore, we have to keep track of the dearchive context of all the scenes.
  257. Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();
  258. string fullPath = "NONE";
  259. TarArchiveReader archive = null;
  260. byte[] data;
  261. TarArchiveReader.TarEntryType entryType;
  262. try
  263. {
  264. FindAndLoadControlFile(out archive, out dearchivedScenes);
  265. while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
  266. {
  267. //m_log.DebugFormat(
  268. // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
  269. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  270. continue;
  271. // Find the scene that this file belongs to
  272. Scene scene;
  273. string filePath;
  274. if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
  275. continue; // this file belongs to a region that we're not loading
  276. DearchiveContext sceneContext = null;
  277. if (scene != null)
  278. {
  279. if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
  280. {
  281. sceneContext = new DearchiveContext(scene);
  282. sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
  283. }
  284. }
  285. // Process the file
  286. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH) && !m_noObjects)
  287. {
  288. sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
  289. }
  290. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
  291. {
  292. if (LoadAsset(filePath, data))
  293. successfulAssetRestores++;
  294. else
  295. failedAssetRestores++;
  296. if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
  297. m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
  298. }
  299. else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_mergeTerrain))
  300. {
  301. LoadTerrain(scene, filePath, data);
  302. }
  303. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  304. {
  305. LoadRegionSettings(scene, filePath, data, dearchivedScenes);
  306. }
  307. else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_mergeParcels))
  308. {
  309. sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
  310. }
  311. else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  312. {
  313. // Ignore, because we already read the control file
  314. }
  315. }
  316. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  317. }
  318. catch (Exception e)
  319. {
  320. m_log.Error(
  321. String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
  322. m_errorMessage += e.ToString();
  323. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  324. return;
  325. }
  326. finally
  327. {
  328. if (archive != null)
  329. archive.Close();
  330. }
  331. if (!m_skipAssets)
  332. {
  333. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  334. if (failedAssetRestores > 0)
  335. {
  336. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  337. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  338. }
  339. }
  340. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  341. {
  342. m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);
  343. if (!m_merge)
  344. {
  345. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  346. sceneContext.Scene.DeleteAllSceneObjects();
  347. }
  348. try
  349. {
  350. LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
  351. LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
  352. // Inform any interested parties that the region has changed. We waited until now so that all
  353. // of the region's objects will be loaded when we send this notification.
  354. IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
  355. if (estateModule != null)
  356. estateModule.TriggerRegionInfoChange();
  357. }
  358. catch (Exception e)
  359. {
  360. m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
  361. m_errorMessage += e.ToString();
  362. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  363. return;
  364. }
  365. }
  366. // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
  367. // that users can enter the scene. If we allow the scripts to start in the loop above
  368. // then they significantly increase the time until the OAR finishes loading.
  369. if (shouldStartScripts)
  370. {
  371. WorkManager.RunInThread(o =>
  372. {
  373. Thread.Sleep(15000);
  374. m_log.Info("[ARCHIVER]: Starting scripts in scene objects...");
  375. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  376. {
  377. foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
  378. {
  379. sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
  380. sceneObject.ResumeScripts();
  381. }
  382. sceneContext.SceneObjects.Clear();
  383. }
  384. m_log.Info("[ARCHIVER]: Start scripts done");
  385. }, null, string.Format("ReadArchiveStartScripts (request {0})", m_requestId));
  386. }
  387. m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
  388. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage);
  389. }
  390. /// <summary>
  391. /// Searches through the files in the archive for the control file, and reads it.
  392. /// We must read the control file first, in order to know which regions are available.
  393. /// </summary>
  394. /// <remarks>
  395. /// In most cases the control file *is* first, since that's how we create archives. However,
  396. /// it's possible that someone rewrote the archive externally so we can't rely on this fact.
  397. /// </remarks>
  398. /// <param name="archive"></param>
  399. /// <param name="dearchivedScenes"></param>
  400. private void FindAndLoadControlFile(out TarArchiveReader archive, out DearchiveScenesInfo dearchivedScenes)
  401. {
  402. archive = new TarArchiveReader(m_loadStream);
  403. dearchivedScenes = new DearchiveScenesInfo();
  404. string filePath;
  405. byte[] data;
  406. TarArchiveReader.TarEntryType entryType;
  407. bool firstFile = true;
  408. while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
  409. {
  410. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  411. continue;
  412. if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  413. {
  414. LoadControlFile(filePath, data, dearchivedScenes);
  415. // Find which scenes are available in the simulator
  416. ArchiveScenesGroup simulatorScenes = new ArchiveScenesGroup();
  417. SceneManager.Instance.ForEachScene(delegate(Scene scene2)
  418. {
  419. simulatorScenes.AddScene(scene2);
  420. });
  421. simulatorScenes.CalcSceneLocations();
  422. dearchivedScenes.SetSimulatorScenes(m_rootScene, simulatorScenes);
  423. // If the control file wasn't the first file then reset the read pointer
  424. if (!firstFile)
  425. {
  426. m_log.Warn("[ARCHIVER]: Control file wasn't the first file in the archive");
  427. if (m_loadStream.CanSeek)
  428. {
  429. m_loadStream.Seek(0, SeekOrigin.Begin);
  430. }
  431. else if (m_loadPath != null)
  432. {
  433. archive.Close();
  434. archive = null;
  435. m_loadStream.Close();
  436. m_loadStream = null;
  437. m_loadStream = new GZipStream(ArchiveHelpers.GetStream(m_loadPath), CompressionMode.Decompress);
  438. archive = new TarArchiveReader(m_loadStream);
  439. }
  440. else
  441. {
  442. // There isn't currently a scenario where this happens, but it's best to add a check just in case
  443. throw new Exception("[ARCHIVER]: Error reading archive: control file wasn't the first file, and the input stream doesn't allow seeking");
  444. }
  445. }
  446. return;
  447. }
  448. firstFile = false;
  449. }
  450. throw new Exception("[ARCHIVER]: Control file not found");
  451. }
  452. /// <summary>
  453. /// Load serialized scene objects.
  454. /// </summary>
  455. protected void LoadObjects(Scene scene, List<string> serialisedSceneObjects, List<SceneObjectGroup> sceneObjects)
  456. {
  457. // Reload serialized prims
  458. m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
  459. // Convert rotation to radians
  460. double rotation = Math.PI * m_rotation / 180f;
  461. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, (float)rotation);
  462. UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject;
  463. IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
  464. int sceneObjectsLoadedCount = 0;
  465. Vector3 boundingExtent = new Vector3(m_boundingOrigin.X + m_boundingSize.X, m_boundingOrigin.Y + m_boundingSize.Y, m_boundingOrigin.Z + m_boundingSize.Z);
  466. int mergeskip = 0;
  467. foreach (string serialisedSceneObject in serialisedSceneObjects)
  468. {
  469. SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
  470. if (m_merge)
  471. {
  472. if(scene.TryGetSceneObjectGroup(sceneObject.UUID, out SceneObjectGroup oldSog))
  473. {
  474. ++mergeskip;
  475. if (m_mergeReplaceObjects)
  476. scene.DeleteSceneObject(oldSog, false);
  477. else
  478. continue;
  479. }
  480. }
  481. Vector3 pos = sceneObject.AbsolutePosition;
  482. if (m_debug)
  483. m_log.DebugFormat("[ARCHIVER]: Loading object from OAR with original scene position {0}.", pos.ToString());
  484. // Happily this does not do much to the object since it hasn't been added to the scene yet
  485. if (!sceneObject.IsAttachment)
  486. {
  487. if (m_rotation != 0f)
  488. {
  489. //fix the rotation center to the middle of the incoming region now as it's otherwise hopelessly confusing on varRegions
  490. //as it only works with objects and terrain (using old Merge method) and not parcels
  491. m_rotationCenter.X = m_incomingRegionSize.X / 2;
  492. m_rotationCenter.Y = m_incomingRegionSize.Y / 2;
  493. // Rotate the object
  494. sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation;
  495. // Get object position relative to rotation axis
  496. Vector3 offset = pos - m_rotationCenter;
  497. // Rotate the object position
  498. offset *= rot;
  499. // Restore the object position back to relative to the region
  500. pos = m_rotationCenter + offset;
  501. if (m_debug) m_log.DebugFormat("[ARCHIVER]: After rotation, object from OAR is at scene position {0}.", pos.ToString());
  502. }
  503. if (m_boundingBox)
  504. {
  505. if (pos.X < m_boundingOrigin.X || pos.X >= boundingExtent.X
  506. || pos.Y < m_boundingOrigin.Y || pos.Y >= boundingExtent.Y
  507. || pos.Z < m_boundingOrigin.Z || pos.Z >= boundingExtent.Z)
  508. {
  509. if (m_debug) m_log.DebugFormat("[ARCHIVER]: Skipping object from OAR in scene because it's position {0} is outside of bounding cube.", pos.ToString());
  510. continue;
  511. }
  512. //adjust object position to be relative to <0,0> so we can apply the displacement
  513. pos.X -= m_boundingOrigin.X;
  514. pos.Y -= m_boundingOrigin.Y;
  515. }
  516. if (m_displacement != Vector3.Zero)
  517. {
  518. pos += m_displacement;
  519. if (m_debug) m_log.DebugFormat("[ARCHIVER]: After displacement, object from OAR is at scene position {0}.", pos.ToString());
  520. }
  521. sceneObject.AbsolutePosition = pos;
  522. }
  523. if (m_debug)
  524. m_log.DebugFormat("[ARCHIVER]: Placing object from OAR in scene at position {0}. ", pos.ToString());
  525. bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
  526. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  527. // on the same region server and multiple examples a single object archive to be imported
  528. // to the same scene (when this is possible).
  529. sceneObject.ResetIDs();
  530. if (isTelehub)
  531. {
  532. // Change the Telehub Object to the new UUID
  533. scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
  534. scene.RegionInfo.RegionSettings.Save();
  535. oldTelehubUUID = UUID.Zero;
  536. }
  537. ModifySceneObject(scene, sceneObject);
  538. if (scene.AddRestoredSceneObject(sceneObject, true, false))
  539. {
  540. sceneObjectsLoadedCount++;
  541. sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
  542. sceneObject.ResumeScripts();
  543. }
  544. }
  545. m_log.InfoFormat("[ARCHIVER]: Loaded {0} scene objects to the scene", sceneObjectsLoadedCount);
  546. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount - mergeskip;
  547. if(mergeskip > 0)
  548. {
  549. if(m_mergeReplaceObjects)
  550. m_log.InfoFormat("[ARCHIVER]: Replaced {0} scene objects", mergeskip);
  551. else
  552. m_log.InfoFormat("[ARCHIVER]: Skipped {0} scene objects that already existed in the scene", mergeskip);
  553. }
  554. if (ignoredObjects > 0)
  555. m_log.WarnFormat("[ARCHIVER]: Ignored {0} possible out of bounds", ignoredObjects);
  556. if (oldTelehubUUID != UUID.Zero)
  557. {
  558. m_log.WarnFormat("[ARCHIVER]: Telehub object not found: {0}", oldTelehubUUID);
  559. scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
  560. scene.RegionInfo.RegionSettings.ClearSpawnPoints();
  561. }
  562. }
  563. /// <summary>
  564. /// Optionally modify a loaded SceneObjectGroup. Currently this just ensures that the
  565. /// User IDs and Group IDs are valid, but other manipulations could be done as well.
  566. /// </summary>
  567. private void ModifySceneObject(Scene scene, SceneObjectGroup sceneObject)
  568. {
  569. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  570. // or creator data is present. Otherwise, use the estate owner instead.
  571. foreach (SceneObjectPart part in sceneObject.Parts)
  572. {
  573. if (string.IsNullOrEmpty(part.CreatorData))
  574. {
  575. if (!ResolveUserUuid(scene, part.CreatorID))
  576. part.CreatorID = m_defaultUser;
  577. }
  578. if (UserManager != null)
  579. UserManager.AddUser(part.CreatorID, part.CreatorData);
  580. if (!(ResolveUserUuid(scene, part.OwnerID) || ResolveGroupUuid(part.OwnerID)))
  581. part.OwnerID = m_defaultUser;
  582. if (!(ResolveUserUuid(scene, part.LastOwnerID) || ResolveGroupUuid(part.LastOwnerID)))
  583. part.LastOwnerID = m_defaultUser;
  584. if (!ResolveGroupUuid(part.GroupID))
  585. part.GroupID = UUID.Zero;
  586. // And zap any troublesome sit target information
  587. // part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  588. // part.SitTargetPosition = new Vector3(0, 0, 0);
  589. // Fix ownership/creator of inventory items
  590. // Not doing so results in inventory items
  591. // being no copy/no mod for everyone
  592. lock (part.TaskInventory)
  593. {
  594. /* avination code disabled for opensim
  595. // And zap any troublesome sit target information
  596. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  597. part.SitTargetPosition = new Vector3(0, 0, 0);
  598. */
  599. // Fix ownership/creator of inventory items
  600. // Not doing so results in inventory items
  601. // being no copy/no mod for everyone
  602. part.TaskInventory.LockItemsForRead(true);
  603. TaskInventoryDictionary inv = part.TaskInventory;
  604. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  605. {
  606. if (!(ResolveUserUuid(scene, kvp.Value.OwnerID) || ResolveGroupUuid(kvp.Value.OwnerID)))
  607. {
  608. kvp.Value.OwnerID = m_defaultUser;
  609. }
  610. if (string.IsNullOrEmpty(kvp.Value.CreatorData))
  611. {
  612. if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
  613. kvp.Value.CreatorID = m_defaultUser;
  614. }
  615. if (UserManager != null)
  616. UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
  617. if (!ResolveGroupUuid(kvp.Value.GroupID))
  618. kvp.Value.GroupID = UUID.Zero;
  619. }
  620. part.TaskInventory.LockItemsForRead(false);
  621. }
  622. }
  623. }
  624. /// <summary>
  625. /// Load serialized parcels.
  626. /// </summary>
  627. /// <param name="scene"></param>
  628. /// <param name="serialisedParcels"></param>
  629. protected void LoadParcels(Scene scene, List<string> serialisedParcels)
  630. {
  631. if(serialisedParcels.Count == 0)
  632. {
  633. m_log.Info("[ARCHIVER]: No parcels to load, or skiping load");
  634. return;
  635. }
  636. // Reload serialized parcels
  637. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  638. List<LandData> landData = new List<LandData>();
  639. ILandObject landObject = scene.RequestModuleInterface<ILandObject>();
  640. List<ILandObject> parcels;
  641. Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
  642. Vector2 displacement = new Vector2(m_displacement.X, m_displacement.Y);
  643. Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
  644. Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
  645. Vector2 regionSize = new Vector2(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY);
  646. // Gather any existing parcels before we add any more. Later as we add parcels we can check if the new parcel
  647. // data overlays any of the old data, and we can modify and remove (if empty) the old parcel so that there's no conflict
  648. bool domerge = m_merge & m_mergeParcels;
  649. parcels = scene.LandChannel.AllParcels();
  650. foreach (string serialisedParcel in serialisedParcels)
  651. {
  652. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  653. bool overrideRegionSize = true; //use the src land parcel data size not the dst region size
  654. bool isEmptyNow;
  655. // create a new LandObject that we can use to manipulate the incoming source parcel data
  656. // this is ok, but just beware that some of the LandObject functions (that we haven't used here) still
  657. // assume we're always using the destination region size
  658. LandData ld = new LandData();
  659. landObject = new LandObject(ld, scene);
  660. landObject.LandData = parcel;
  661. bool[,] srcLandBitmap = landObject.ConvertBytesToLandBitmap(overrideRegionSize);
  662. if (landObject.IsLandBitmapEmpty(srcLandBitmap))
  663. {
  664. m_log.InfoFormat("[ARCHIVER]: Skipping source parcel {0} with GlobalID: {1} LocalID: {2} that has no claimed land.",
  665. parcel.Name, parcel.GlobalID, parcel.LocalID);
  666. continue;
  667. }
  668. //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for source parcel: {0} with GlobalID: {1} LocalID: {2}.",
  669. // parcel.Name, parcel.GlobalID, parcel.LocalID);
  670. //landObject.DebugLandBitmap(srcLandBitmap);
  671. bool[,] dstLandBitmap = landObject.RemapLandBitmap(srcLandBitmap, displacement, m_rotation, boundingOrigin, boundingSize, regionSize, out isEmptyNow);
  672. if (isEmptyNow)
  673. {
  674. m_log.WarnFormat("[ARCHIVER]: Not adding destination parcel {0} with GlobalID: {1} LocalID: {2} because, after applying rotation, bounding and displacement, it has no claimed land.",
  675. parcel.Name, parcel.GlobalID, parcel.LocalID);
  676. continue;
  677. }
  678. //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for destination parcel: {0} with GlobalID: {1} LocalID: {2} after applying rotation, bounding and displacement.",
  679. // parcel.Name, parcel.GlobalID, parcel.LocalID);
  680. //landObject.DebugLandBitmap(dstLandBitmap);
  681. landObject.LandBitmap = dstLandBitmap;
  682. parcel.Bitmap = landObject.ConvertLandBitmapToBytes();
  683. if (domerge)
  684. {
  685. // give the remapped parcel a new GlobalID, in case we're using the same OAR twice and a bounding cube, displacement and --merge
  686. parcel.GlobalID = UUID.Random();
  687. //now check if the area of this new incoming parcel overlays an area in any existing parcels
  688. //and if so modify or lose the existing parcels
  689. for (int i = 0; i < parcels.Count; i++)
  690. {
  691. if (parcels[i] != null)
  692. {
  693. bool[,] modLandBitmap = parcels[i].ConvertBytesToLandBitmap(overrideRegionSize);
  694. modLandBitmap = parcels[i].RemoveFromLandBitmap(modLandBitmap, dstLandBitmap, out isEmptyNow);
  695. if (isEmptyNow)
  696. {
  697. parcels[i] = null;
  698. }
  699. else
  700. {
  701. parcels[i].LandBitmap = modLandBitmap;
  702. parcels[i].LandData.Bitmap = parcels[i].ConvertLandBitmapToBytes();
  703. }
  704. }
  705. }
  706. }
  707. // Validate User and Group UUID's
  708. if (!ResolveGroupUuid(parcel.GroupID))
  709. parcel.GroupID = UUID.Zero;
  710. if (parcel.IsGroupOwned)
  711. {
  712. if (parcel.GroupID != UUID.Zero)
  713. {
  714. // In group-owned parcels, OwnerID=GroupID. This should already be the case, but let's make sure.
  715. parcel.OwnerID = parcel.GroupID;
  716. }
  717. else
  718. {
  719. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  720. parcel.IsGroupOwned = false;
  721. }
  722. }
  723. else
  724. {
  725. if (!ResolveUserUuid(scene, parcel.OwnerID))
  726. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  727. }
  728. List<LandAccessEntry> accessList = new List<LandAccessEntry>();
  729. foreach (LandAccessEntry entry in parcel.ParcelAccessList)
  730. {
  731. if (ResolveUserUuid(scene, entry.AgentID))
  732. accessList.Add(entry);
  733. // else, drop this access rule
  734. }
  735. parcel.ParcelAccessList = accessList;
  736. if (m_debug) m_log.DebugFormat("[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
  737. parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
  738. landData.Add(parcel);
  739. }
  740. m_log.InfoFormat("[ARCHIVER]: Clearing {0} parcels.", parcels.Count);
  741. bool setupDefaultParcel = (landData.Count == 0);
  742. scene.LandChannel.Clear(setupDefaultParcel);
  743. if (domerge)
  744. {
  745. int j = 0;
  746. for (int i = 0; i < parcels.Count; i++) //if merging then we need to also add back in any existing parcels
  747. {
  748. if (parcels[i] != null)
  749. {
  750. landData.Add(parcels[i].LandData);
  751. j++;
  752. }
  753. }
  754. m_log.InfoFormat("[ARCHIVER]: Keeping {0} old parcels.", j);
  755. }
  756. scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  757. m_log.InfoFormat("[ARCHIVER]: Added {0} total parcels.", landData.Count);
  758. }
  759. /// <summary>
  760. /// Look up the given user id to check whether it's one that is valid for this grid.
  761. /// </summary>
  762. /// <param name="scene"></param>
  763. /// <param name="uuid"></param>
  764. /// <returns></returns>
  765. private bool ResolveUserUuid(Scene scene, UUID uuid)
  766. {
  767. lock (m_validUserUuids)
  768. {
  769. if (!m_validUserUuids.ContainsKey(uuid))
  770. {
  771. // Note: we call GetUserAccount() inside the lock because this UserID is likely
  772. // to occur many times, and we only want to query the users service once.
  773. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
  774. m_validUserUuids.Add(uuid, account != null);
  775. }
  776. return m_validUserUuids[uuid];
  777. }
  778. }
  779. /// <summary>
  780. /// Look up the given group id to check whether it's one that is valid for this grid.
  781. /// </summary>
  782. /// <param name="uuid"></param>
  783. /// <returns></returns>
  784. private bool ResolveGroupUuid(UUID uuid)
  785. {
  786. lock (m_validGroupUuids)
  787. {
  788. if (!m_validGroupUuids.ContainsKey(uuid))
  789. {
  790. bool exists;
  791. if (m_groupsModule == null)
  792. {
  793. exists = false;
  794. }
  795. else
  796. {
  797. // Note: we call GetGroupRecord() inside the lock because this GroupID is likely
  798. // to occur many times, and we only want to query the groups service once.
  799. exists = (m_groupsModule.GetGroupRecord(uuid) != null);
  800. }
  801. m_validGroupUuids.Add(uuid, exists);
  802. }
  803. return m_validGroupUuids[uuid];
  804. }
  805. }
  806. /// Load an asset
  807. /// </summary>
  808. /// <param name="assetFilename"></param>
  809. /// <param name="data"></param>
  810. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  811. private bool LoadAsset(string assetPath, byte[] data)
  812. {
  813. // Right now we're nastily obtaining the UUID from the filename
  814. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  815. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  816. if (i == -1)
  817. {
  818. m_log.ErrorFormat(
  819. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  820. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  821. return false;
  822. }
  823. string extension = filename.Substring(i);
  824. string uuid = filename.Remove(filename.Length - extension.Length);
  825. if (m_assetService.GetMetadata(uuid) != null)
  826. {
  827. sbyte asype = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  828. // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
  829. return true;
  830. }
  831. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  832. {
  833. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  834. if (assetType == (sbyte)AssetType.Unknown)
  835. {
  836. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  837. }
  838. else if (assetType == (sbyte)AssetType.Object)
  839. {
  840. data = SceneObjectSerializer.ModifySerializedObject(UUID.Parse(uuid), data,
  841. sog =>
  842. {
  843. ModifySceneObject(m_rootScene, sog);
  844. return true;
  845. });
  846. if (data == null)
  847. return false;
  848. }
  849. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  850. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  851. asset.Data = data;
  852. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  853. // exists.
  854. m_assetService.Store(asset);
  855. /**
  856. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  857. * it might be best done when dearchive takes place on a separate thread
  858. if (asset.Type=AssetType.Texture)
  859. {
  860. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  861. if (cacheLayerDecode != null)
  862. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  863. }
  864. */
  865. return true;
  866. }
  867. else
  868. {
  869. m_log.ErrorFormat(
  870. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  871. assetPath, extension);
  872. return false;
  873. }
  874. }
  875. /// <summary>
  876. /// Load region settings data
  877. /// </summary>
  878. /// <param name="scene"></param>
  879. /// <param name="settingsPath"></param>
  880. /// <param name="data"></param>
  881. /// <param name="dearchivedScenes"></param>
  882. /// <returns>
  883. /// true if settings were loaded successfully, false otherwise
  884. /// </returns>
  885. private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
  886. {
  887. RegionSettings loadedRegionSettings;
  888. ViewerEnvironment regionEnv = null;
  889. try
  890. {
  891. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data, out regionEnv);
  892. }
  893. catch (Exception e)
  894. {
  895. m_log.ErrorFormat(
  896. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  897. settingsPath, e);
  898. return false;
  899. }
  900. IEnvironmentModule mEnv = scene.RequestModuleInterface<IEnvironmentModule>();
  901. if(mEnv != null)
  902. {
  903. mEnv.StoreOnRegion(regionEnv);
  904. mEnv.WindlightRefresh(0);
  905. }
  906. RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
  907. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  908. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  909. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  910. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  911. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  912. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  913. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  914. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  915. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  916. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  917. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  918. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  919. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  920. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  921. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  922. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  923. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  924. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  925. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  926. currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
  927. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  928. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  929. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  930. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  931. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  932. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  933. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  934. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  935. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  936. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  937. currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
  938. currentRegionSettings.ClearSpawnPoints();
  939. foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
  940. currentRegionSettings.AddSpawnPoint(sp);
  941. currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
  942. currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
  943. currentRegionSettings.CacheID = UUID.Random();
  944. currentRegionSettings.Save();
  945. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  946. if (estateModule != null)
  947. estateModule.sendRegionHandshakeToAll();
  948. return true;
  949. }
  950. /// <summary>
  951. /// Load terrain data
  952. /// </summary>
  953. /// <param name="scene"></param>
  954. /// <param name="terrainPath"></param>
  955. /// <param name="data"></param>
  956. /// <returns>
  957. /// true if terrain was resolved successfully, false otherwise.
  958. /// </returns>
  959. private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
  960. {
  961. ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
  962. using (MemoryStream ms = new MemoryStream(data))
  963. {
  964. if (m_displacement != Vector3.Zero || m_rotation != 0f || m_boundingBox)
  965. {
  966. Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
  967. Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
  968. terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, boundingOrigin, boundingSize, ms); ;
  969. }
  970. else
  971. {
  972. terrainModule.LoadFromStream(terrainPath, ms);
  973. }
  974. }
  975. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  976. return true;
  977. }
  978. /// <summary>
  979. /// Load oar control file
  980. /// </summary>
  981. /// <param name="path"></param>
  982. /// <param name="data"></param>
  983. /// <param name="dearchivedScenes"></param>
  984. public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
  985. {
  986. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
  987. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  988. XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  989. // Loaded metadata will be empty if no information exists in the archive
  990. dearchivedScenes.LoadedCreationDateTime = 0;
  991. dearchivedScenes.DefaultOriginalID = "";
  992. bool multiRegion = false;
  993. while (xtr.Read())
  994. {
  995. if (xtr.NodeType == XmlNodeType.Element)
  996. {
  997. if (xtr.Name.ToString() == "archive")
  998. {
  999. int majorVersion = int.Parse(xtr["major_version"]);
  1000. int minorVersion = int.Parse(xtr["minor_version"]);
  1001. string version = string.Format("{0}.{1}", majorVersion, minorVersion);
  1002. if (majorVersion > MAX_MAJOR_VERSION)
  1003. {
  1004. throw new Exception(
  1005. string.Format(
  1006. "The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below",
  1007. majorVersion, MAX_MAJOR_VERSION));
  1008. }
  1009. m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
  1010. }
  1011. else if (xtr.Name.ToString() == "datetime")
  1012. {
  1013. int value;
  1014. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  1015. dearchivedScenes.LoadedCreationDateTime = value;
  1016. }
  1017. else if (xtr.Name.ToString() == "row")
  1018. {
  1019. multiRegion = true;
  1020. dearchivedScenes.StartRow();
  1021. }
  1022. else if (xtr.Name.ToString() == "region")
  1023. {
  1024. dearchivedScenes.StartRegion();
  1025. }
  1026. else if (xtr.Name.ToString() == "id")
  1027. {
  1028. string id = xtr.ReadElementContentAsString();
  1029. dearchivedScenes.DefaultOriginalID = id;
  1030. if(multiRegion)
  1031. dearchivedScenes.SetRegionOriginalID(id);
  1032. }
  1033. else if (xtr.Name.ToString() == "dir")
  1034. {
  1035. dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
  1036. }
  1037. else if (xtr.Name.ToString() == "size_in_meters")
  1038. {
  1039. Vector3 value;
  1040. string size = "<" + xtr.ReadElementContentAsString() + ",0>";
  1041. if (Vector3.TryParse(size, out value))
  1042. {
  1043. m_incomingRegionSize = value;
  1044. if(multiRegion)
  1045. dearchivedScenes.SetRegionSize(m_incomingRegionSize);
  1046. m_log.DebugFormat("[ARCHIVER]: Found region_size info {0}",
  1047. m_incomingRegionSize.ToString());
  1048. }
  1049. }
  1050. }
  1051. }
  1052. dearchivedScenes.MultiRegionFormat = multiRegion;
  1053. if (!multiRegion)
  1054. {
  1055. // Add the single scene
  1056. dearchivedScenes.StartRow();
  1057. dearchivedScenes.StartRegion();
  1058. dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
  1059. dearchivedScenes.SetRegionDirectory("");
  1060. dearchivedScenes.SetRegionSize(m_incomingRegionSize);
  1061. }
  1062. ControlFileLoaded = true;
  1063. if(xtr != null)
  1064. xtr.Close();
  1065. return dearchivedScenes;
  1066. }
  1067. }
  1068. }