ArchiveReadRequest.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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_boundingOrigin.Z = Constants.MinSimulationHeight;
  191. m_boundingSize = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, Constants.MaxSimulationHeight - Constants.MinSimulationHeight);
  192. if (options.ContainsKey("bounding-origin"))
  193. {
  194. Vector3 boOption = (Vector3)options["bounding-origin"];
  195. if (boOption != m_boundingOrigin)
  196. {
  197. m_boundingOrigin = boOption;
  198. }
  199. m_boundingBox = true;
  200. }
  201. if (options.ContainsKey("bounding-size"))
  202. {
  203. Vector3 bsOption = (Vector3)options["bounding-size"];
  204. bool clip = false;
  205. if (bsOption.X <= 0 || bsOption.X > m_boundingSize.X)
  206. {
  207. bsOption.X = m_boundingSize.X;
  208. clip = true;
  209. }
  210. if (bsOption.Y <= 0 || bsOption.Y > m_boundingSize.Y)
  211. {
  212. bsOption.Y = m_boundingSize.Y;
  213. clip = true;
  214. }
  215. if (bsOption != m_boundingSize)
  216. {
  217. m_boundingSize = bsOption;
  218. m_boundingBox = true;
  219. }
  220. if (clip) m_log.InfoFormat("[ARCHIVER]: The bounding cube specified is larger than the destination region! Clipping to {0}.", m_boundingSize.ToString());
  221. }
  222. m_debug = options.ContainsKey("debug");
  223. // Zero can never be a valid user id (or group)
  224. m_validUserUuids[UUID.Zero] = false;
  225. m_validGroupUuids[UUID.Zero] = false;
  226. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  227. m_assetService = m_rootScene.AssetService;
  228. }
  229. public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object> options)
  230. {
  231. m_rootScene = scene;
  232. m_loadPath = null;
  233. m_loadStream = loadStream;
  234. m_skipAssets = options.ContainsKey("skipAssets");
  235. m_merge = options.ContainsKey("merge");
  236. m_mergeReplaceObjects = options.ContainsKey("mReplaceObjects");
  237. m_requestId = requestId;
  238. m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner;
  239. // Zero can never be a valid user id
  240. m_validUserUuids[UUID.Zero] = false;
  241. m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>();
  242. m_assetService = m_rootScene.AssetService;
  243. }
  244. /// <summary>
  245. /// Dearchive the region embodied in this request.
  246. /// </summary>
  247. public void DearchiveRegion()
  248. {
  249. DearchiveRegion(true);
  250. }
  251. public void DearchiveRegion(bool shouldStartScripts)
  252. {
  253. int successfulAssetRestores = 0;
  254. int failedAssetRestores = 0;
  255. DearchiveScenesInfo dearchivedScenes;
  256. // We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
  257. // Therefore, we have to keep track of the dearchive context of all the scenes.
  258. Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();
  259. string fullPath = "NONE";
  260. TarArchiveReader archive = null;
  261. byte[] data;
  262. TarArchiveReader.TarEntryType entryType;
  263. try
  264. {
  265. FindAndLoadControlFile(out archive, out dearchivedScenes);
  266. while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
  267. {
  268. //m_log.DebugFormat(
  269. // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
  270. if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
  271. continue;
  272. // Find the scene that this file belongs to
  273. Scene scene;
  274. string filePath;
  275. if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
  276. continue; // this file belongs to a region that we're not loading
  277. DearchiveContext sceneContext = null;
  278. if (scene != null)
  279. {
  280. if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
  281. {
  282. sceneContext = new DearchiveContext(scene);
  283. sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
  284. }
  285. }
  286. // Process the file
  287. if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH) && !m_noObjects)
  288. {
  289. sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
  290. }
  291. else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
  292. {
  293. if (LoadAsset(filePath, data))
  294. successfulAssetRestores++;
  295. else
  296. failedAssetRestores++;
  297. if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
  298. m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
  299. }
  300. else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_mergeTerrain))
  301. {
  302. LoadTerrain(scene, filePath, data);
  303. }
  304. else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
  305. {
  306. LoadRegionSettings(scene, filePath, data, dearchivedScenes);
  307. }
  308. else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_mergeParcels))
  309. {
  310. sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
  311. }
  312. else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
  313. {
  314. // Ignore, because we already read the control file
  315. }
  316. }
  317. //m_log.Debug("[ARCHIVER]: Reached end of archive");
  318. }
  319. catch (Exception e)
  320. {
  321. m_log.Error(
  322. String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
  323. m_errorMessage += e.ToString();
  324. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  325. return;
  326. }
  327. finally
  328. {
  329. if (archive != null)
  330. archive.Close();
  331. }
  332. if (!m_skipAssets)
  333. {
  334. m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
  335. if (failedAssetRestores > 0)
  336. {
  337. m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
  338. m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
  339. }
  340. }
  341. foreach (DearchiveContext sceneContext in sceneContexts.Values)
  342. {
  343. m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);
  344. if (!m_merge)
  345. {
  346. m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
  347. sceneContext.Scene.DeleteAllSceneObjects();
  348. }
  349. try
  350. {
  351. LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
  352. LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
  353. // Inform any interested parties that the region has changed. We waited until now so that all
  354. // of the region's objects will be loaded when we send this notification.
  355. IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
  356. if (estateModule != null)
  357. estateModule.TriggerRegionInfoChange();
  358. }
  359. catch (Exception e)
  360. {
  361. m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
  362. m_errorMessage += e.ToString();
  363. m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
  364. return;
  365. }
  366. }
  367. // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
  368. // that users can enter the scene. If we allow the scripts to start in the loop above
  369. // then they significantly increase the time until the OAR finishes loading.
  370. if (shouldStartScripts)
  371. {
  372. WorkManager.RunInThread(o =>
  373. {
  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 (pos.X < 0 || pos.X >= scene.RegionInfo.RegionSizeX
  520. || pos.Y < 0 || pos.Y >= scene.RegionInfo.RegionSizeY
  521. || pos.Z < Constants.MinSimulationHeight || pos.Z > Constants.MaxSimulationHeight)
  522. {
  523. if (m_debug) m_log.DebugFormat("[ARCHIVER]: Skipping object from OAR After displacement clip {0}.", pos.ToString());
  524. continue;
  525. }
  526. if (m_debug) m_log.DebugFormat("[ARCHIVER]: After displacement, object from OAR is at scene position {0}.", pos.ToString());
  527. }
  528. sceneObject.AbsolutePosition = pos;
  529. }
  530. if (m_debug)
  531. m_log.DebugFormat("[ARCHIVER]: Placing object from OAR in scene at position {0}. ", pos.ToString());
  532. bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero);
  533. // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
  534. // on the same region server and multiple examples a single object archive to be imported
  535. // to the same scene (when this is possible).
  536. sceneObject.ResetIDs();
  537. if (isTelehub)
  538. {
  539. // Change the Telehub Object to the new UUID
  540. scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID;
  541. scene.RegionInfo.RegionSettings.Save();
  542. oldTelehubUUID = UUID.Zero;
  543. }
  544. ModifySceneObject(scene, sceneObject);
  545. if (scene.AddRestoredSceneObject(sceneObject, true, false))
  546. {
  547. sceneObjectsLoadedCount++;
  548. sceneObjects.Add(sceneObject);
  549. //sceneObject.CreateScriptInstances(0, false, scene.DefaultScriptEngine, 0);
  550. //sceneObject.ResumeScripts();
  551. }
  552. }
  553. m_log.InfoFormat("[ARCHIVER]: Loaded {0} scene objects to the scene", sceneObjectsLoadedCount);
  554. int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount - mergeskip;
  555. if(mergeskip > 0)
  556. {
  557. if(m_mergeReplaceObjects)
  558. m_log.InfoFormat("[ARCHIVER]: Replaced {0} scene objects", mergeskip);
  559. else
  560. m_log.InfoFormat("[ARCHIVER]: Skipped {0} scene objects that already existed in the scene", mergeskip);
  561. }
  562. if (ignoredObjects > 0)
  563. m_log.WarnFormat("[ARCHIVER]: Ignored {0} possible out of bounds", ignoredObjects);
  564. if (oldTelehubUUID != UUID.Zero)
  565. {
  566. m_log.WarnFormat("[ARCHIVER]: Telehub object not found: {0}", oldTelehubUUID);
  567. scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero;
  568. scene.RegionInfo.RegionSettings.ClearSpawnPoints();
  569. }
  570. }
  571. /// <summary>
  572. /// Optionally modify a loaded SceneObjectGroup. Currently this just ensures that the
  573. /// User IDs and Group IDs are valid, but other manipulations could be done as well.
  574. /// </summary>
  575. private void ModifySceneObject(Scene scene, SceneObjectGroup sceneObject)
  576. {
  577. // Try to retain the original creator/owner/lastowner if their uuid is present on this grid
  578. // or creator data is present. Otherwise, use the estate owner instead.
  579. foreach (SceneObjectPart part in sceneObject.Parts)
  580. {
  581. if (string.IsNullOrEmpty(part.CreatorData))
  582. {
  583. if (!ResolveUserUuid(scene, part.CreatorID))
  584. part.CreatorID = m_defaultUser;
  585. }
  586. if (UserManager != null)
  587. UserManager.AddCreatorUser(part.CreatorID, part.CreatorData);
  588. if (!(ResolveUserUuid(scene, part.OwnerID) || ResolveGroupUuid(part.OwnerID)))
  589. part.OwnerID = m_defaultUser;
  590. if (!(ResolveUserUuid(scene, part.LastOwnerID) || ResolveGroupUuid(part.LastOwnerID)))
  591. part.LastOwnerID = m_defaultUser;
  592. if (!ResolveGroupUuid(part.GroupID))
  593. part.GroupID = UUID.Zero;
  594. // And zap any troublesome sit target information
  595. // part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  596. // part.SitTargetPosition = new Vector3(0, 0, 0);
  597. // Fix ownership/creator of inventory items
  598. // Not doing so results in inventory items
  599. // being no copy/no mod for everyone
  600. lock (part.TaskInventory)
  601. {
  602. /* avination code disabled for opensim
  603. // And zap any troublesome sit target information
  604. part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
  605. part.SitTargetPosition = new Vector3(0, 0, 0);
  606. */
  607. // Fix ownership/creator of inventory items
  608. // Not doing so results in inventory items
  609. // being no copy/no mod for everyone
  610. part.TaskInventory.LockItemsForRead(true);
  611. TaskInventoryDictionary inv = part.TaskInventory;
  612. foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
  613. {
  614. if (!(ResolveUserUuid(scene, kvp.Value.OwnerID) || ResolveGroupUuid(kvp.Value.OwnerID)))
  615. {
  616. kvp.Value.OwnerID = m_defaultUser;
  617. }
  618. if (string.IsNullOrEmpty(kvp.Value.CreatorData))
  619. {
  620. if (!ResolveUserUuid(scene, kvp.Value.CreatorID))
  621. kvp.Value.CreatorID = m_defaultUser;
  622. }
  623. if (UserManager != null)
  624. UserManager.AddCreatorUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
  625. if (!ResolveGroupUuid(kvp.Value.GroupID))
  626. kvp.Value.GroupID = UUID.Zero;
  627. }
  628. part.TaskInventory.LockItemsForRead(false);
  629. }
  630. }
  631. }
  632. /// <summary>
  633. /// Load serialized parcels.
  634. /// </summary>
  635. /// <param name="scene"></param>
  636. /// <param name="serialisedParcels"></param>
  637. protected void LoadParcels(Scene scene, List<string> serialisedParcels)
  638. {
  639. if(serialisedParcels.Count == 0)
  640. {
  641. m_log.Info("[ARCHIVER]: No parcels to load, or skiping load");
  642. return;
  643. }
  644. // Reload serialized parcels
  645. m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
  646. List<LandData> landData = new List<LandData>();
  647. ILandObject landObject = scene.RequestModuleInterface<ILandObject>();
  648. List<ILandObject> parcels;
  649. Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f);
  650. Vector2 displacement = new Vector2(m_displacement.X, m_displacement.Y);
  651. Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
  652. Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
  653. Vector2 regionSize = new Vector2(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY);
  654. // Gather any existing parcels before we add any more. Later as we add parcels we can check if the new parcel
  655. // data overlays any of the old data, and we can modify and remove (if empty) the old parcel so that there's no conflict
  656. bool domerge = m_merge & m_mergeParcels;
  657. parcels = scene.LandChannel.AllParcels();
  658. foreach (string serialisedParcel in serialisedParcels)
  659. {
  660. LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
  661. bool overrideRegionSize = true; //use the src land parcel data size not the dst region size
  662. bool isEmptyNow;
  663. // create a new LandObject that we can use to manipulate the incoming source parcel data
  664. // this is ok, but just beware that some of the LandObject functions (that we haven't used here) still
  665. // assume we're always using the destination region size
  666. LandData ld = new LandData();
  667. landObject = new LandObject(ld, scene);
  668. landObject.LandData = parcel;
  669. bool[,] srcLandBitmap = landObject.ConvertBytesToLandBitmap(overrideRegionSize);
  670. if (landObject.IsLandBitmapEmpty(srcLandBitmap))
  671. {
  672. m_log.InfoFormat("[ARCHIVER]: Skipping source parcel {0} with GlobalID: {1} LocalID: {2} that has no claimed land.",
  673. parcel.Name, parcel.GlobalID, parcel.LocalID);
  674. continue;
  675. }
  676. //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for source parcel: {0} with GlobalID: {1} LocalID: {2}.",
  677. // parcel.Name, parcel.GlobalID, parcel.LocalID);
  678. //landObject.DebugLandBitmap(srcLandBitmap);
  679. bool[,] dstLandBitmap = landObject.RemapLandBitmap(srcLandBitmap, displacement, m_rotation, boundingOrigin, boundingSize, regionSize, out isEmptyNow);
  680. if (isEmptyNow)
  681. {
  682. 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.",
  683. parcel.Name, parcel.GlobalID, parcel.LocalID);
  684. continue;
  685. }
  686. //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for destination parcel: {0} with GlobalID: {1} LocalID: {2} after applying rotation, bounding and displacement.",
  687. // parcel.Name, parcel.GlobalID, parcel.LocalID);
  688. //landObject.DebugLandBitmap(dstLandBitmap);
  689. landObject.LandBitmap = dstLandBitmap;
  690. parcel.Bitmap = landObject.ConvertLandBitmapToBytes();
  691. if (domerge)
  692. {
  693. // give the remapped parcel a new GlobalID, in case we're using the same OAR twice and a bounding cube, displacement and --merge
  694. parcel.GlobalID = UUID.Random();
  695. //now check if the area of this new incoming parcel overlays an area in any existing parcels
  696. //and if so modify or lose the existing parcels
  697. for (int i = 0; i < parcels.Count; i++)
  698. {
  699. if (parcels[i] != null)
  700. {
  701. bool[,] modLandBitmap = parcels[i].ConvertBytesToLandBitmap(overrideRegionSize);
  702. modLandBitmap = parcels[i].RemoveFromLandBitmap(modLandBitmap, dstLandBitmap, out isEmptyNow);
  703. if (isEmptyNow)
  704. {
  705. parcels[i] = null;
  706. }
  707. else
  708. {
  709. parcels[i].LandBitmap = modLandBitmap;
  710. parcels[i].LandData.Bitmap = parcels[i].ConvertLandBitmapToBytes();
  711. }
  712. }
  713. }
  714. }
  715. // Validate User and Group UUID's
  716. if (!ResolveGroupUuid(parcel.GroupID))
  717. parcel.GroupID = UUID.Zero;
  718. if (parcel.IsGroupOwned)
  719. {
  720. if (parcel.GroupID != UUID.Zero)
  721. {
  722. // In group-owned parcels, OwnerID=GroupID. This should already be the case, but let's make sure.
  723. parcel.OwnerID = parcel.GroupID;
  724. }
  725. else
  726. {
  727. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  728. parcel.IsGroupOwned = false;
  729. }
  730. }
  731. else
  732. {
  733. if (!ResolveUserUuid(scene, parcel.OwnerID))
  734. parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner;
  735. }
  736. List<LandAccessEntry> accessList = new List<LandAccessEntry>();
  737. foreach (LandAccessEntry entry in parcel.ParcelAccessList)
  738. {
  739. if (ResolveUserUuid(scene, entry.AgentID))
  740. accessList.Add(entry);
  741. // else, drop this access rule
  742. }
  743. parcel.ParcelAccessList = accessList;
  744. if (m_debug) m_log.DebugFormat("[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}",
  745. parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area);
  746. landData.Add(parcel);
  747. }
  748. m_log.InfoFormat("[ARCHIVER]: Clearing {0} parcels.", parcels.Count);
  749. bool setupDefaultParcel = (landData.Count == 0);
  750. scene.LandChannel.Clear(setupDefaultParcel);
  751. if (domerge)
  752. {
  753. int j = 0;
  754. for (int i = 0; i < parcels.Count; i++) //if merging then we need to also add back in any existing parcels
  755. {
  756. if (parcels[i] != null)
  757. {
  758. landData.Add(parcels[i].LandData);
  759. j++;
  760. }
  761. }
  762. m_log.InfoFormat("[ARCHIVER]: Keeping {0} old parcels.", j);
  763. }
  764. scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
  765. m_log.InfoFormat("[ARCHIVER]: Added {0} total parcels.", landData.Count);
  766. }
  767. /// <summary>
  768. /// Look up the given user id to check whether it's one that is valid for this grid.
  769. /// </summary>
  770. /// <param name="scene"></param>
  771. /// <param name="uuid"></param>
  772. /// <returns></returns>
  773. private bool ResolveUserUuid(Scene scene, UUID uuid)
  774. {
  775. lock (m_validUserUuids)
  776. {
  777. if (!m_validUserUuids.ContainsKey(uuid))
  778. {
  779. // Note: we call GetUserAccount() inside the lock because this UserID is likely
  780. // to occur many times, and we only want to query the users service once.
  781. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid);
  782. m_validUserUuids.Add(uuid, account != null);
  783. }
  784. return m_validUserUuids[uuid];
  785. }
  786. }
  787. /// <summary>
  788. /// Look up the given group id to check whether it's one that is valid for this grid.
  789. /// </summary>
  790. /// <param name="uuid"></param>
  791. /// <returns></returns>
  792. private bool ResolveGroupUuid(UUID uuid)
  793. {
  794. lock (m_validGroupUuids)
  795. {
  796. if (!m_validGroupUuids.ContainsKey(uuid))
  797. {
  798. bool exists;
  799. if (m_groupsModule == null)
  800. {
  801. exists = false;
  802. }
  803. else
  804. {
  805. // Note: we call GetGroupRecord() inside the lock because this GroupID is likely
  806. // to occur many times, and we only want to query the groups service once.
  807. exists = (m_groupsModule.GetGroupRecord(uuid) != null);
  808. }
  809. m_validGroupUuids.Add(uuid, exists);
  810. }
  811. return m_validGroupUuids[uuid];
  812. }
  813. }
  814. /// Load an asset
  815. /// </summary>
  816. /// <param name="assetFilename"></param>
  817. /// <param name="data"></param>
  818. /// <returns>true if asset was successfully loaded, false otherwise</returns>
  819. private bool LoadAsset(string assetPath, byte[] data)
  820. {
  821. // Right now we're nastily obtaining the UUID from the filename
  822. string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
  823. int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  824. if (i == -1)
  825. {
  826. m_log.ErrorFormat(
  827. "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
  828. assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
  829. return false;
  830. }
  831. string extension = filename.Substring(i);
  832. string uuid = filename.Remove(filename.Length - extension.Length);
  833. if (m_assetService.GetMetadata(uuid) != null)
  834. {
  835. sbyte asype = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  836. // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid);
  837. return true;
  838. }
  839. if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
  840. {
  841. sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
  842. if (assetType == (sbyte)AssetType.Unknown)
  843. {
  844. m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
  845. }
  846. else if (assetType == (sbyte)AssetType.Object)
  847. {
  848. data = SceneObjectSerializer.ModifySerializedObject(UUID.Parse(uuid), data,
  849. sog =>
  850. {
  851. ModifySceneObject(m_rootScene, sog);
  852. return true;
  853. });
  854. if (data == null)
  855. return false;
  856. }
  857. //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
  858. AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
  859. asset.Data = data;
  860. // We're relying on the asset service to do the sensible thing and not store the asset if it already
  861. // exists.
  862. m_assetService.Store(asset);
  863. /**
  864. * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
  865. * it might be best done when dearchive takes place on a separate thread
  866. if (asset.Type=AssetType.Texture)
  867. {
  868. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  869. if (cacheLayerDecode != null)
  870. cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
  871. }
  872. */
  873. return true;
  874. }
  875. else
  876. {
  877. m_log.ErrorFormat(
  878. "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
  879. assetPath, extension);
  880. return false;
  881. }
  882. }
  883. /// <summary>
  884. /// Load region settings data
  885. /// </summary>
  886. /// <param name="scene"></param>
  887. /// <param name="settingsPath"></param>
  888. /// <param name="data"></param>
  889. /// <param name="dearchivedScenes"></param>
  890. /// <returns>
  891. /// true if settings were loaded successfully, false otherwise
  892. /// </returns>
  893. private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes)
  894. {
  895. RegionSettings loadedRegionSettings;
  896. ViewerEnvironment regionEnv = null;
  897. try
  898. {
  899. loadedRegionSettings = RegionSettingsSerializer.Deserialize(data, out regionEnv);
  900. }
  901. catch (Exception e)
  902. {
  903. m_log.ErrorFormat(
  904. "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
  905. settingsPath, e);
  906. return false;
  907. }
  908. IEnvironmentModule mEnv = scene.RequestModuleInterface<IEnvironmentModule>();
  909. if(mEnv != null)
  910. {
  911. mEnv.StoreOnRegion(regionEnv);
  912. mEnv.WindlightRefresh(0);
  913. }
  914. RegionSettings currentRegionSettings = scene.RegionInfo.RegionSettings;
  915. currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
  916. currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
  917. currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
  918. currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
  919. currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
  920. currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
  921. currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
  922. currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
  923. currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
  924. currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
  925. currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
  926. currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
  927. currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
  928. currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
  929. currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
  930. currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
  931. currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
  932. currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
  933. currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
  934. currentRegionSettings.SunPosition = loadedRegionSettings.SunPosition;
  935. currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
  936. currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
  937. currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
  938. currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
  939. currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
  940. currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
  941. currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
  942. currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
  943. currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
  944. currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
  945. currentRegionSettings.TelehubObject = loadedRegionSettings.TelehubObject;
  946. currentRegionSettings.ClearSpawnPoints();
  947. foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints())
  948. currentRegionSettings.AddSpawnPoint(sp);
  949. currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime;
  950. currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString();
  951. currentRegionSettings.CacheID = UUID.Random();
  952. currentRegionSettings.Save();
  953. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>();
  954. if (estateModule != null)
  955. estateModule.sendRegionHandshakeToAll();
  956. return true;
  957. }
  958. /// <summary>
  959. /// Load terrain data
  960. /// </summary>
  961. /// <param name="scene"></param>
  962. /// <param name="terrainPath"></param>
  963. /// <param name="data"></param>
  964. /// <returns>
  965. /// true if terrain was resolved successfully, false otherwise.
  966. /// </returns>
  967. private bool LoadTerrain(Scene scene, string terrainPath, byte[] data)
  968. {
  969. ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
  970. using (MemoryStream ms = new MemoryStream(data))
  971. {
  972. if (m_displacement != Vector3.Zero || m_rotation != 0f || m_boundingBox)
  973. {
  974. Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y);
  975. Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y);
  976. terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, boundingOrigin, boundingSize, ms); ;
  977. }
  978. else
  979. {
  980. terrainModule.LoadFromStream(terrainPath, ms);
  981. }
  982. }
  983. m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
  984. return true;
  985. }
  986. /// <summary>
  987. /// Load oar control file
  988. /// </summary>
  989. /// <param name="path"></param>
  990. /// <param name="data"></param>
  991. /// <param name="dearchivedScenes"></param>
  992. public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes)
  993. {
  994. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
  995. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
  996. XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
  997. // Loaded metadata will be empty if no information exists in the archive
  998. dearchivedScenes.LoadedCreationDateTime = 0;
  999. dearchivedScenes.DefaultOriginalID = "";
  1000. bool multiRegion = false;
  1001. while (xtr.Read())
  1002. {
  1003. if (xtr.NodeType == XmlNodeType.Element)
  1004. {
  1005. if (xtr.Name.ToString() == "archive")
  1006. {
  1007. int majorVersion = int.Parse(xtr["major_version"]);
  1008. int minorVersion = int.Parse(xtr["minor_version"]);
  1009. string version = string.Format("{0}.{1}", majorVersion, minorVersion);
  1010. if (majorVersion > MAX_MAJOR_VERSION)
  1011. {
  1012. throw new Exception(
  1013. string.Format(
  1014. "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",
  1015. majorVersion, MAX_MAJOR_VERSION));
  1016. }
  1017. m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
  1018. }
  1019. else if (xtr.Name.ToString() == "datetime")
  1020. {
  1021. int value;
  1022. if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
  1023. dearchivedScenes.LoadedCreationDateTime = value;
  1024. }
  1025. else if (xtr.Name.ToString() == "row")
  1026. {
  1027. multiRegion = true;
  1028. dearchivedScenes.StartRow();
  1029. }
  1030. else if (xtr.Name.ToString() == "region")
  1031. {
  1032. dearchivedScenes.StartRegion();
  1033. }
  1034. else if (xtr.Name.ToString() == "id")
  1035. {
  1036. string id = xtr.ReadElementContentAsString();
  1037. dearchivedScenes.DefaultOriginalID = id;
  1038. if(multiRegion)
  1039. dearchivedScenes.SetRegionOriginalID(id);
  1040. }
  1041. else if (xtr.Name.ToString() == "dir")
  1042. {
  1043. dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString());
  1044. }
  1045. else if (xtr.Name.ToString() == "size_in_meters")
  1046. {
  1047. Vector3 value;
  1048. string size = "<" + xtr.ReadElementContentAsString() + ",0>";
  1049. if (Vector3.TryParse(size, out value))
  1050. {
  1051. m_incomingRegionSize = value;
  1052. if(multiRegion)
  1053. dearchivedScenes.SetRegionSize(m_incomingRegionSize);
  1054. m_log.DebugFormat("[ARCHIVER]: Found region_size info {0}",
  1055. m_incomingRegionSize.ToString());
  1056. }
  1057. }
  1058. }
  1059. }
  1060. dearchivedScenes.MultiRegionFormat = multiRegion;
  1061. if (!multiRegion)
  1062. {
  1063. // Add the single scene
  1064. dearchivedScenes.StartRow();
  1065. dearchivedScenes.StartRegion();
  1066. dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID);
  1067. dearchivedScenes.SetRegionDirectory("");
  1068. dearchivedScenes.SetRegionSize(m_incomingRegionSize);
  1069. }
  1070. ControlFileLoaded = true;
  1071. if(xtr != null)
  1072. xtr.Close();
  1073. return dearchivedScenes;
  1074. }
  1075. }
  1076. }