ArchiveReadRequest.cs 56 KB

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