Meshmerizer.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  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. //#define SPAM
  28. using System;
  29. using System.Collections.Generic;
  30. using OpenSim.Framework;
  31. using OpenSim.Region.Framework.Scenes;
  32. using OpenSim.Region.Framework.Interfaces;
  33. using OpenSim.Region.PhysicsModules.SharedBase;
  34. using OpenSim.Region.PhysicsModules.ConvexDecompositionDotNet;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using System.Drawing;
  38. using System.Threading;
  39. using System.IO.Compression;
  40. using PrimMesher;
  41. using log4net;
  42. using Nini.Config;
  43. using System.Reflection;
  44. using System.IO;
  45. using Mono.Addins;
  46. namespace OpenSim.Region.PhysicsModule.ubODEMeshing
  47. {
  48. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ubODEMeshmerizer")]
  49. public class ubMeshmerizer : IMesher, INonSharedRegionModule
  50. {
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. // Setting baseDir to a path will enable the dumping of raw files
  53. // raw files can be imported by blender so a visual inspection of the results can be done
  54. const float floatPI = (float)Math.PI;
  55. private static string cacheControlFilename = "cntr";
  56. private bool m_Enabled = false;
  57. public static object diskLock = new object();
  58. public bool doMeshFileCache = true;
  59. public bool doCacheExpire = true;
  60. public string cachePath = "MeshCache";
  61. public TimeSpan CacheExpire;
  62. // const string baseDir = "rawFiles";
  63. private const string baseDir = null; //"rawFiles";
  64. private bool useMeshiesPhysicsMesh = true;
  65. private bool doConvexPrims = true;
  66. private bool doConvexSculpts = true;
  67. private Dictionary<AMeshKey, Mesh> m_uniqueMeshes = new Dictionary<AMeshKey, Mesh>();
  68. private Dictionary<AMeshKey, Mesh> m_uniqueReleasedMeshes = new Dictionary<AMeshKey, Mesh>();
  69. #region INonSharedRegionModule
  70. public string Name
  71. {
  72. get { return "ubODEMeshmerizer"; }
  73. }
  74. public Type ReplaceableInterface
  75. {
  76. get { return null; }
  77. }
  78. public void Initialise(IConfigSource config)
  79. {
  80. IConfig start_config = config.Configs["Startup"];
  81. string mesher = start_config.GetString("meshing", string.Empty);
  82. if (mesher == Name)
  83. {
  84. float fcache = 48.0f;
  85. // float fcache = 0.02f;
  86. IConfig mesh_config = config.Configs["Mesh"];
  87. if (mesh_config != null)
  88. {
  89. useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
  90. doConvexPrims = mesh_config.GetBoolean("ConvexPrims",doConvexPrims);
  91. doConvexSculpts = mesh_config.GetBoolean("ConvexSculpts",doConvexPrims);
  92. doMeshFileCache = mesh_config.GetBoolean("MeshFileCache", doMeshFileCache);
  93. cachePath = mesh_config.GetString("MeshFileCachePath", cachePath);
  94. fcache = mesh_config.GetFloat("MeshFileCacheExpireHours", fcache);
  95. doCacheExpire = mesh_config.GetBoolean("MeshFileCacheDoExpire", doCacheExpire);
  96. m_Enabled = true;
  97. }
  98. CacheExpire = TimeSpan.FromHours(fcache);
  99. if(String.IsNullOrEmpty(cachePath))
  100. doMeshFileCache = false;
  101. if(doMeshFileCache)
  102. {
  103. if(!checkCache())
  104. {
  105. doMeshFileCache = false;
  106. doCacheExpire = false;
  107. }
  108. }
  109. else
  110. doCacheExpire = false;
  111. }
  112. }
  113. public void Close()
  114. {
  115. }
  116. public void AddRegion(Scene scene)
  117. {
  118. if (!m_Enabled)
  119. return;
  120. scene.RegisterModuleInterface<IMesher>(this);
  121. }
  122. public void RemoveRegion(Scene scene)
  123. {
  124. if (!m_Enabled)
  125. return;
  126. scene.UnregisterModuleInterface<IMesher>(this);
  127. }
  128. public void RegionLoaded(Scene scene)
  129. {
  130. if (!m_Enabled)
  131. return;
  132. }
  133. #endregion
  134. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  135. {
  136. m_log.Error(message);
  137. m_log.Error("\nPrim Name: " + primName);
  138. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  139. }
  140. /// <summary>
  141. /// Add a submesh to an existing list of coords and faces.
  142. /// </summary>
  143. /// <param name="subMeshData"></param>
  144. /// <param name="size">Size of entire object</param>
  145. /// <param name="coords"></param>
  146. /// <param name="faces"></param>
  147. private void AddSubMesh(OSDMap subMeshData, List<Coord> coords, List<Face> faces)
  148. {
  149. // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
  150. // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
  151. // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
  152. // geometry for this submesh.
  153. if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
  154. return;
  155. OpenMetaverse.Vector3 posMax;
  156. OpenMetaverse.Vector3 posMin;
  157. if (subMeshData.ContainsKey("PositionDomain"))
  158. {
  159. posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
  160. posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
  161. }
  162. else
  163. {
  164. posMax = new Vector3(0.5f, 0.5f, 0.5f);
  165. posMin = new Vector3(-0.5f, -0.5f, -0.5f);
  166. }
  167. ushort faceIndexOffset = (ushort)coords.Count;
  168. byte[] posBytes = subMeshData["Position"].AsBinary();
  169. for (int i = 0; i < posBytes.Length; i += 6)
  170. {
  171. ushort uX = Utils.BytesToUInt16(posBytes, i);
  172. ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
  173. ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
  174. Coord c = new Coord(
  175. Utils.UInt16ToFloat(uX, posMin.X, posMax.X),
  176. Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y),
  177. Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z));
  178. coords.Add(c);
  179. }
  180. byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
  181. for (int i = 0; i < triangleBytes.Length; i += 6)
  182. {
  183. ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
  184. ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
  185. ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
  186. Face f = new Face(v1, v2, v3);
  187. faces.Add(f);
  188. }
  189. }
  190. /// <summary>
  191. /// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
  192. /// </summary>
  193. /// <param name="primName"></param>
  194. /// <param name="primShape"></param>
  195. /// <param name="size"></param>
  196. /// <param name="lod"></param>
  197. /// <returns></returns>
  198. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, float lod, bool convex)
  199. {
  200. // m_log.DebugFormat(
  201. // "[MESH]: Creating physics proxy for {0}, shape {1}",
  202. // primName, (OpenMetaverse.SculptType)primShape.SculptType);
  203. List<Coord> coords;
  204. List<Face> faces;
  205. bool needsConvexProcessing = convex;
  206. if (primShape.SculptEntry)
  207. {
  208. if (((SculptType)primShape.SculptType) == SculptType.Mesh)
  209. {
  210. if (!useMeshiesPhysicsMesh)
  211. return null;
  212. try
  213. {
  214. if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, out coords, out faces, convex))
  215. return null;
  216. needsConvexProcessing = false;
  217. }
  218. catch
  219. {
  220. m_log.ErrorFormat("[MESH]: fail to process mesh asset for prim {0}", primName);
  221. return null;
  222. }
  223. }
  224. else
  225. {
  226. try
  227. {
  228. if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, lod, out coords, out faces))
  229. return null;
  230. needsConvexProcessing &= doConvexSculpts;
  231. }
  232. catch
  233. {
  234. m_log.ErrorFormat("[MESH]: fail to process sculpt map for prim {0}", primName);
  235. return null;
  236. }
  237. }
  238. }
  239. else
  240. {
  241. try
  242. {
  243. if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, lod, convex, out coords, out faces))
  244. return null;
  245. needsConvexProcessing &= doConvexPrims;
  246. }
  247. catch
  248. {
  249. m_log.ErrorFormat("[MESH]: fail to process shape parameters for prim {0}", primName);
  250. return null;
  251. }
  252. }
  253. int numCoords = coords.Count;
  254. int numFaces = faces.Count;
  255. if(numCoords < 3 || (!needsConvexProcessing && numFaces < 1))
  256. {
  257. m_log.ErrorFormat("[ubODEMesh]: invalid degenerated mesh for prim {0} ignored", primName);
  258. return null;
  259. }
  260. if(needsConvexProcessing)
  261. {
  262. List<Coord> convexcoords;
  263. List<Face> convexfaces;
  264. if(CreateBoundingHull(coords, out convexcoords, out convexfaces) && convexcoords != null && convexfaces != null)
  265. {
  266. coords.Clear();
  267. coords = convexcoords;
  268. numCoords = coords.Count;
  269. faces.Clear();
  270. faces = convexfaces;
  271. numFaces = faces.Count;
  272. }
  273. else
  274. m_log.ErrorFormat("[ubMESH]: failed to create convex for {0} using normal mesh", primName);
  275. }
  276. Mesh mesh = new Mesh(true);
  277. // Add the corresponding triangles to the mesh
  278. for (int i = 0; i < numFaces; i++)
  279. {
  280. Face f = faces[i];
  281. mesh.Add(new Triangle(coords[f.v1].X, coords[f.v1].Y, coords[f.v1].Z,
  282. coords[f.v2].X, coords[f.v2].Y, coords[f.v2].Z,
  283. coords[f.v3].X, coords[f.v3].Y, coords[f.v3].Z));
  284. }
  285. coords.Clear();
  286. faces.Clear();
  287. if(mesh.numberVertices() < 3 || mesh.numberTriangles() < 1)
  288. {
  289. m_log.ErrorFormat("[ubODEMesh]: invalid degenerated mesh for prim {0} ignored", primName);
  290. return null;
  291. }
  292. primShape.SculptData = Utils.EmptyBytes;
  293. return mesh;
  294. }
  295. /// <summary>
  296. /// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
  297. /// </summary>
  298. /// <param name="primName"></param>
  299. /// <param name="primShape"></param>
  300. /// <param name="size"></param>
  301. /// <param name="coords">Coords are added to this list by the method.</param>
  302. /// <param name="faces">Faces are added to this list by the method.</param>
  303. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  304. private bool GenerateCoordsAndFacesFromPrimMeshData(
  305. string primName, PrimitiveBaseShape primShape, out List<Coord> coords, out List<Face> faces, bool convex)
  306. {
  307. // m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
  308. // for ubOde we have a diferent mesh use priority
  309. // priority is to use full mesh then decomposition
  310. // SL does the oposite
  311. bool usemesh = false;
  312. coords = new List<Coord>();
  313. faces = new List<Face>();
  314. OSD meshOsd = null;
  315. if (primShape.SculptData == null || primShape.SculptData.Length <= 0)
  316. {
  317. // m_log.InfoFormat("[MESH]: asset data for {0} is zero length", primName);
  318. return false;
  319. }
  320. long start = 0;
  321. using (MemoryStream data = new MemoryStream(primShape.SculptData))
  322. {
  323. try
  324. {
  325. OSD osd = OSDParser.DeserializeLLSDBinary(data);
  326. if (osd is OSDMap)
  327. meshOsd = (OSDMap)osd;
  328. else
  329. {
  330. m_log.WarnFormat("[Mesh}: unable to cast mesh asset to OSDMap prim: {0}",primName);
  331. return false;
  332. }
  333. }
  334. catch (Exception e)
  335. {
  336. m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
  337. return false;
  338. }
  339. start = data.Position;
  340. }
  341. if (meshOsd is OSDMap)
  342. {
  343. OSDMap physicsParms = null;
  344. OSDMap map = (OSDMap)meshOsd;
  345. if (!convex)
  346. {
  347. if (map.ContainsKey("physics_shape"))
  348. physicsParms = (OSDMap)map["physics_shape"]; // old asset format
  349. else if (map.ContainsKey("physics_mesh"))
  350. physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
  351. if (physicsParms != null)
  352. usemesh = true;
  353. }
  354. if(!usemesh && (map.ContainsKey("physics_convex")))
  355. physicsParms = (OSDMap)map["physics_convex"];
  356. if (physicsParms == null)
  357. {
  358. //m_log.WarnFormat("[MESH]: unknown mesh type for prim {0}",primName);
  359. return false;
  360. }
  361. int physOffset = physicsParms["offset"].AsInteger() + (int)start;
  362. int physSize = physicsParms["size"].AsInteger();
  363. if (physOffset < 0 || physSize == 0)
  364. return false; // no mesh data in asset
  365. OSD decodedMeshOsd = new OSD();
  366. try
  367. {
  368. using (MemoryStream outMs = new MemoryStream(4 * physSize))
  369. {
  370. using (MemoryStream inMs = new MemoryStream(primShape.SculptData, physOffset, physSize))
  371. {
  372. using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
  373. {
  374. byte[] readBuffer = new byte[8192];
  375. inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
  376. int readLen = 0;
  377. while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  378. outMs.Write(readBuffer, 0, readLen);
  379. }
  380. }
  381. outMs.Seek(0, SeekOrigin.Begin);
  382. decodedMeshOsd = OSDParser.DeserializeLLSDBinary(outMs);
  383. }
  384. }
  385. catch (Exception e)
  386. {
  387. m_log.Error("[MESH]: exception decoding physical mesh prim " + primName +" : " + e.ToString());
  388. return false;
  389. }
  390. if (usemesh)
  391. {
  392. OSDArray decodedMeshOsdArray = null;
  393. // physics_shape is an array of OSDMaps, one for each submesh
  394. if (decodedMeshOsd is OSDArray)
  395. {
  396. // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
  397. decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
  398. foreach (OSD subMeshOsd in decodedMeshOsdArray)
  399. {
  400. if (subMeshOsd is OSDMap)
  401. AddSubMesh(subMeshOsd as OSDMap, coords, faces);
  402. }
  403. }
  404. }
  405. else
  406. {
  407. OSDMap cmap = (OSDMap)decodedMeshOsd;
  408. if (cmap == null)
  409. return false;
  410. byte[] data;
  411. List<float3> vs = new List<float3>();
  412. PHullResult hullr = new PHullResult();
  413. float3 f3;
  414. Coord c;
  415. Face f;
  416. Vector3 range;
  417. Vector3 min;
  418. const float invMaxU16 = 1.0f / 65535f;
  419. int t1;
  420. int t2;
  421. int t3;
  422. int i;
  423. int nverts;
  424. int nindexs;
  425. if (cmap.ContainsKey("Max"))
  426. range = cmap["Max"].AsVector3();
  427. else
  428. range = new Vector3(0.5f, 0.5f, 0.5f);
  429. if (cmap.ContainsKey("Min"))
  430. min = cmap["Min"].AsVector3();
  431. else
  432. min = new Vector3(-0.5f, -0.5f, -0.5f);
  433. range = range - min;
  434. range *= invMaxU16;
  435. if(!convex)
  436. {
  437. // if mesh data not present and not convex then we need convex decomposition data
  438. if (cmap.ContainsKey("HullList") && cmap.ContainsKey("Positions"))
  439. {
  440. List<int> hsizes = new List<int>();
  441. int totalpoints = 0;
  442. data = cmap["HullList"].AsBinary();
  443. for (i = 0; i < data.Length; i++)
  444. {
  445. t1 = data[i];
  446. if (t1 == 0)
  447. t1 = 256;
  448. totalpoints += t1;
  449. hsizes.Add(t1);
  450. }
  451. data = cmap["Positions"].AsBinary();
  452. int ptr = 0;
  453. int vertsoffset = 0;
  454. if (totalpoints == data.Length / 6) // 2 bytes per coord, 3 coords per point
  455. {
  456. foreach (int hullsize in hsizes)
  457. {
  458. for (i = 0; i < hullsize; i++ )
  459. {
  460. t1 = data[ptr++];
  461. t1 += data[ptr++] << 8;
  462. t2 = data[ptr++];
  463. t2 += data[ptr++] << 8;
  464. t3 = data[ptr++];
  465. t3 += data[ptr++] << 8;
  466. f3 = new float3((t1 * range.X + min.X),
  467. (t2 * range.Y + min.Y),
  468. (t3 * range.Z + min.Z));
  469. vs.Add(f3);
  470. }
  471. if(hullsize <3)
  472. {
  473. vs.Clear();
  474. continue;
  475. }
  476. if (hullsize <5)
  477. {
  478. foreach (float3 point in vs)
  479. {
  480. c.X = point.x;
  481. c.Y = point.y;
  482. c.Z = point.z;
  483. coords.Add(c);
  484. }
  485. f = new Face(vertsoffset, vertsoffset + 1, vertsoffset + 2);
  486. faces.Add(f);
  487. if (hullsize == 4)
  488. {
  489. // not sure about orientation..
  490. f = new Face(vertsoffset, vertsoffset + 2, vertsoffset + 3);
  491. faces.Add(f);
  492. f = new Face(vertsoffset, vertsoffset + 3, vertsoffset + 1);
  493. faces.Add(f);
  494. f = new Face(vertsoffset + 3, vertsoffset + 2, vertsoffset + 1);
  495. faces.Add(f);
  496. }
  497. vertsoffset += vs.Count;
  498. vs.Clear();
  499. continue;
  500. }
  501. List<int> indices;
  502. if (!HullUtils.ComputeHull(vs, out indices))
  503. {
  504. vs.Clear();
  505. continue;
  506. }
  507. nverts = vs.Count;
  508. nindexs = indices.Count;
  509. if (nindexs % 3 != 0)
  510. {
  511. vs.Clear();
  512. continue;
  513. }
  514. for (i = 0; i < nverts; i++)
  515. {
  516. c.X = vs[i].x;
  517. c.Y = vs[i].y;
  518. c.Z = vs[i].z;
  519. coords.Add(c);
  520. }
  521. for (i = 0; i < nindexs; i += 3)
  522. {
  523. t1 = indices[i];
  524. if (t1 > nverts)
  525. break;
  526. t2 = indices[i + 1];
  527. if (t2 > nverts)
  528. break;
  529. t3 = indices[i + 2];
  530. if (t3 > nverts)
  531. break;
  532. f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
  533. faces.Add(f);
  534. }
  535. vertsoffset += nverts;
  536. vs.Clear();
  537. }
  538. }
  539. if (coords.Count > 0 && faces.Count > 0)
  540. return true;
  541. }
  542. else
  543. {
  544. // if neither mesh or decomposition present, warn and use convex
  545. //m_log.WarnFormat("[MESH]: Data for PRIM shape type ( mesh or decomposition) not found for prim {0}",primName);
  546. }
  547. }
  548. vs.Clear();
  549. if (cmap.ContainsKey("BoundingVerts"))
  550. {
  551. data = cmap["BoundingVerts"].AsBinary();
  552. for (i = 0; i < data.Length; )
  553. {
  554. t1 = data[i++];
  555. t1 += data[i++] << 8;
  556. t2 = data[i++];
  557. t2 += data[i++] << 8;
  558. t3 = data[i++];
  559. t3 += data[i++] << 8;
  560. f3 = new float3((t1 * range.X + min.X),
  561. (t2 * range.Y + min.Y),
  562. (t3 * range.Z + min.Z));
  563. vs.Add(f3);
  564. }
  565. nverts = vs.Count;
  566. if (nverts < 3)
  567. {
  568. vs.Clear();
  569. return false;
  570. }
  571. if (nverts < 5)
  572. {
  573. foreach (float3 point in vs)
  574. {
  575. c.X = point.x;
  576. c.Y = point.y;
  577. c.Z = point.z;
  578. coords.Add(c);
  579. }
  580. f = new Face(0, 1, 2);
  581. faces.Add(f);
  582. if (nverts == 4)
  583. {
  584. f = new Face(0, 2, 3);
  585. faces.Add(f);
  586. f = new Face(0, 3, 1);
  587. faces.Add(f);
  588. f = new Face( 3, 2, 1);
  589. faces.Add(f);
  590. }
  591. vs.Clear();
  592. return true;
  593. }
  594. List<int> indices;
  595. if (!HullUtils.ComputeHull(vs, out indices))
  596. return false;
  597. nindexs = indices.Count;
  598. if (nindexs % 3 != 0)
  599. return false;
  600. for (i = 0; i < nverts; i++)
  601. {
  602. c.X = vs[i].x;
  603. c.Y = vs[i].y;
  604. c.Z = vs[i].z;
  605. coords.Add(c);
  606. }
  607. for (i = 0; i < nindexs; i += 3)
  608. {
  609. t1 = indices[i];
  610. if (t1 > nverts)
  611. break;
  612. t2 = indices[i + 1];
  613. if (t2 > nverts)
  614. break;
  615. t3 = indices[i + 2];
  616. if (t3 > nverts)
  617. break;
  618. f = new Face(t1, t2, t3);
  619. faces.Add(f);
  620. }
  621. vs.Clear();
  622. if (coords.Count > 0 && faces.Count > 0)
  623. return true;
  624. }
  625. else
  626. return false;
  627. }
  628. }
  629. return true;
  630. }
  631. /// <summary>
  632. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  633. /// </summary>
  634. /// <param name="primName"></param>
  635. /// <param name="primShape"></param>
  636. /// <param name="size"></param>
  637. /// <param name="lod"></param>
  638. /// <param name="coords">Coords are added to this list by the method.</param>
  639. /// <param name="faces">Faces are added to this list by the method.</param>
  640. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  641. private bool GenerateCoordsAndFacesFromPrimSculptData(
  642. string primName, PrimitiveBaseShape primShape, float lod, out List<Coord> coords, out List<Face> faces)
  643. {
  644. coords = new List<Coord>();
  645. faces = new List<Face>();
  646. PrimMesher.SculptMesh sculptMesh;
  647. Image idata = null;
  648. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  649. return false;
  650. try
  651. {
  652. OpenMetaverse.Imaging.ManagedImage unusedData;
  653. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
  654. unusedData = null;
  655. if (idata == null)
  656. {
  657. // In some cases it seems that the decode can return a null bitmap without throwing
  658. // an exception
  659. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  660. return false;
  661. }
  662. }
  663. catch (DllNotFoundException)
  664. {
  665. m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!");
  666. return false;
  667. }
  668. catch (IndexOutOfRangeException)
  669. {
  670. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  671. return false;
  672. }
  673. catch (Exception ex)
  674. {
  675. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  676. return false;
  677. }
  678. PrimMesher.SculptMesh.SculptType sculptType;
  679. // remove mirror and invert bits
  680. OpenMetaverse.SculptType pbsSculptType = ((OpenMetaverse.SculptType)(primShape.SculptType & 0x3f));
  681. switch (pbsSculptType)
  682. {
  683. case OpenMetaverse.SculptType.Cylinder:
  684. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  685. break;
  686. case OpenMetaverse.SculptType.Plane:
  687. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  688. break;
  689. case OpenMetaverse.SculptType.Torus:
  690. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  691. break;
  692. case OpenMetaverse.SculptType.Sphere:
  693. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  694. break;
  695. default:
  696. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  697. break;
  698. }
  699. bool mirror = ((primShape.SculptType & 128) != 0);
  700. bool invert = ((primShape.SculptType & 64) != 0);
  701. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, mirror, invert);
  702. idata.Dispose();
  703. // sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  704. coords = sculptMesh.coords;
  705. faces = sculptMesh.faces;
  706. return true;
  707. }
  708. /// <summary>
  709. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  710. /// </summary>
  711. /// <param name="primName"></param>
  712. /// <param name="primShape"></param>
  713. /// <param name="size"></param>
  714. /// <param name="coords">Coords are added to this list by the method.</param>
  715. /// <param name="faces">Faces are added to this list by the method.</param>
  716. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  717. private bool GenerateCoordsAndFacesFromPrimShapeData(
  718. string primName, PrimitiveBaseShape primShape, float lod, bool convex,
  719. out List<Coord> coords, out List<Face> faces)
  720. {
  721. PrimMesh primMesh;
  722. coords = new List<Coord>();
  723. faces = new List<Face>();
  724. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  725. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  726. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  727. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  728. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  729. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  730. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  731. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  732. if (profileBegin < 0.0f)
  733. profileBegin = 0.0f;
  734. if (profileEnd < 0.02f)
  735. profileEnd = 0.02f;
  736. else if (profileEnd > 1.0f)
  737. profileEnd = 1.0f;
  738. if (profileBegin >= profileEnd)
  739. profileBegin = profileEnd - 0.02f;
  740. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  741. if(convex)
  742. profileHollow = 0.0f;
  743. else if (profileHollow > 0.95f)
  744. profileHollow = 0.95f;
  745. int sides = 4;
  746. LevelOfDetail iLOD = (LevelOfDetail)lod;
  747. byte profshape = (byte)(primShape.ProfileCurve & 0x07);
  748. if (profshape == (byte)ProfileShape.EquilateralTriangle
  749. || profshape == (byte)ProfileShape.IsometricTriangle
  750. || profshape == (byte)ProfileShape.RightTriangle)
  751. sides = 3;
  752. else if (profshape == (byte)ProfileShape.Circle)
  753. {
  754. switch (iLOD)
  755. {
  756. case LevelOfDetail.High: sides = 24; break;
  757. case LevelOfDetail.Medium: sides = 12; break;
  758. case LevelOfDetail.Low: sides = 6; break;
  759. case LevelOfDetail.VeryLow: sides = 3; break;
  760. default: sides = 24; break;
  761. }
  762. }
  763. else if (profshape == (byte)ProfileShape.HalfCircle)
  764. { // half circle, prim is a sphere
  765. switch (iLOD)
  766. {
  767. case LevelOfDetail.High: sides = 24; break;
  768. case LevelOfDetail.Medium: sides = 12; break;
  769. case LevelOfDetail.Low: sides = 6; break;
  770. case LevelOfDetail.VeryLow: sides = 3; break;
  771. default: sides = 24; break;
  772. }
  773. profileBegin = 0.5f * profileBegin + 0.5f;
  774. profileEnd = 0.5f * profileEnd + 0.5f;
  775. }
  776. int hollowSides = sides;
  777. if (primShape.HollowShape == HollowShape.Circle)
  778. {
  779. switch (iLOD)
  780. {
  781. case LevelOfDetail.High: hollowSides = 24; break;
  782. case LevelOfDetail.Medium: hollowSides = 12; break;
  783. case LevelOfDetail.Low: hollowSides = 6; break;
  784. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  785. default: hollowSides = 24; break;
  786. }
  787. }
  788. else if (primShape.HollowShape == HollowShape.Square)
  789. hollowSides = 4;
  790. else if (primShape.HollowShape == HollowShape.Triangle)
  791. {
  792. if (profshape == (byte)ProfileShape.HalfCircle)
  793. hollowSides = 6;
  794. else
  795. hollowSides = 3;
  796. }
  797. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  798. if (primMesh.errorMessage != null)
  799. if (primMesh.errorMessage.Length > 0)
  800. m_log.Error("[ERROR] " + primMesh.errorMessage);
  801. primMesh.topShearX = pathShearX;
  802. primMesh.topShearY = pathShearY;
  803. primMesh.pathCutBegin = pathBegin;
  804. primMesh.pathCutEnd = pathEnd;
  805. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  806. {
  807. primMesh.twistBegin = (float)(primShape.PathTwistBegin * (floatPI * 0.01f));
  808. primMesh.twistEnd = (float)(primShape.PathTwist * (floatPI * 0.01f));
  809. primMesh.taperX = pathScaleX;
  810. primMesh.taperY = pathScaleY;
  811. #if SPAM
  812. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  813. #endif
  814. try
  815. {
  816. primMesh.Extrude(PathType.Linear); ;
  817. }
  818. catch (Exception ex)
  819. {
  820. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  821. return false;
  822. }
  823. }
  824. else
  825. {
  826. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  827. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  828. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  829. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  830. primMesh.skew = 0.01f * primShape.PathSkew;
  831. primMesh.twistBegin = (float)(primShape.PathTwistBegin * (floatPI * 0.02f));
  832. primMesh.twistEnd = (float)(primShape.PathTwistBegin * (floatPI * 0.02f));
  833. primMesh.taperX = primShape.PathTaperX * 0.01f;
  834. primMesh.taperY = primShape.PathTaperY * 0.01f;
  835. if(profshape == (byte)ProfileShape.HalfCircle)
  836. {
  837. if(primMesh.holeSizeY < 0.01f)
  838. primMesh.holeSizeY = 0.01f;
  839. else if(primMesh.holeSizeY > 1.0f)
  840. primMesh.holeSizeY = 1.0f;
  841. }
  842. #if SPAM
  843. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  844. #endif
  845. try
  846. {
  847. primMesh.Extrude(PathType.Circular);
  848. }
  849. catch (Exception ex)
  850. {
  851. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  852. return false;
  853. }
  854. }
  855. // primMesh.DumpRaw(baseDir, primName, "primMesh");
  856. coords = primMesh.coords;
  857. faces = primMesh.faces;
  858. return true;
  859. }
  860. public AMeshKey GetMeshUniqueKey(PrimitiveBaseShape primShape, Vector3 size, byte lod, bool convex)
  861. {
  862. AMeshKey key = new AMeshKey();
  863. Byte[] someBytes;
  864. key.hashB = 5181;
  865. key.hashC = 5181;
  866. ulong hash = 5381;
  867. if (primShape.SculptEntry)
  868. {
  869. key.uuid = primShape.SculptTexture;
  870. key.hashC = mdjb2(key.hashC, primShape.SculptType);
  871. key.hashC = mdjb2(key.hashC, primShape.PCode);
  872. }
  873. else
  874. {
  875. hash = mdjb2(hash, primShape.PathCurve);
  876. hash = mdjb2(hash, (byte)primShape.HollowShape);
  877. hash = mdjb2(hash, (byte)primShape.ProfileShape);
  878. hash = mdjb2(hash, primShape.PathBegin);
  879. hash = mdjb2(hash, primShape.PathEnd);
  880. hash = mdjb2(hash, primShape.PathScaleX);
  881. hash = mdjb2(hash, primShape.PathScaleY);
  882. hash = mdjb2(hash, primShape.PathShearX);
  883. key.hashA = hash;
  884. hash = key.hashB;
  885. hash = mdjb2(hash, primShape.PathShearY);
  886. hash = mdjb2(hash, (byte)primShape.PathTwist);
  887. hash = mdjb2(hash, (byte)primShape.PathTwistBegin);
  888. hash = mdjb2(hash, (byte)primShape.PathRadiusOffset);
  889. hash = mdjb2(hash, (byte)primShape.PathTaperX);
  890. hash = mdjb2(hash, (byte)primShape.PathTaperY);
  891. hash = mdjb2(hash, primShape.PathRevolutions);
  892. hash = mdjb2(hash, (byte)primShape.PathSkew);
  893. hash = mdjb2(hash, primShape.ProfileBegin);
  894. hash = mdjb2(hash, primShape.ProfileEnd);
  895. hash = mdjb2(hash, primShape.ProfileHollow);
  896. hash = mdjb2(hash, primShape.PCode);
  897. key.hashB = hash;
  898. }
  899. hash = key.hashC;
  900. hash = mdjb2(hash, lod);
  901. if (size == m_MeshUnitSize)
  902. {
  903. hash = hash << 8;
  904. hash |= 8;
  905. }
  906. else
  907. {
  908. someBytes = size.GetBytes();
  909. for (int i = 0; i < someBytes.Length; i++)
  910. hash = mdjb2(hash, someBytes[i]);
  911. hash = hash << 8;
  912. }
  913. if (convex)
  914. hash |= 4;
  915. if (primShape.SculptEntry)
  916. {
  917. hash |= 1;
  918. if (primShape.SculptType == (byte)SculptType.Mesh)
  919. hash |= 2;
  920. }
  921. key.hashC = hash;
  922. return key;
  923. }
  924. private ulong mdjb2(ulong hash, byte c)
  925. {
  926. return ((hash << 5) + hash) + (ulong)c;
  927. }
  928. private ulong mdjb2(ulong hash, ushort c)
  929. {
  930. hash = ((hash << 5) + hash) + (ulong)((byte)c);
  931. return ((hash << 5) + hash) + (ulong)(c >> 8);
  932. }
  933. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  934. {
  935. return CreateMesh(primName, primShape, size, lod, false,false,false);
  936. }
  937. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  938. {
  939. return CreateMesh(primName, primShape, size, lod, false,false,false);
  940. }
  941. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, bool convex, bool forOde)
  942. {
  943. return CreateMesh(primName, primShape, size, lod, false, false, false);
  944. }
  945. public IMesh GetMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex)
  946. {
  947. Mesh mesh = null;
  948. if (size.X < 0.01f) size.X = 0.01f;
  949. if (size.Y < 0.01f) size.Y = 0.01f;
  950. if (size.Z < 0.01f) size.Z = 0.01f;
  951. AMeshKey key = GetMeshUniqueKey(primShape, size, (byte)lod, convex);
  952. lock (m_uniqueMeshes)
  953. {
  954. m_uniqueMeshes.TryGetValue(key, out mesh);
  955. if (mesh != null)
  956. {
  957. mesh.RefCount++;
  958. return mesh;
  959. }
  960. // try to find a identical mesh on meshs recently released
  961. lock (m_uniqueReleasedMeshes)
  962. {
  963. m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
  964. if (mesh != null)
  965. {
  966. m_uniqueReleasedMeshes.Remove(key);
  967. try
  968. {
  969. m_uniqueMeshes.Add(key, mesh);
  970. }
  971. catch { }
  972. mesh.RefCount = 1;
  973. return mesh;
  974. }
  975. }
  976. }
  977. return null;
  978. }
  979. private static Vector3 m_MeshUnitSize = new Vector3(1.0f, 1.0f, 1.0f);
  980. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex, bool forOde)
  981. {
  982. #if SPAM
  983. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  984. #endif
  985. Mesh mesh = null;
  986. if (size.X < 0.01f) size.X = 0.01f;
  987. if (size.Y < 0.01f) size.Y = 0.01f;
  988. if (size.Z < 0.01f) size.Z = 0.01f;
  989. // try to find a identical mesh on meshs in use
  990. AMeshKey key = GetMeshUniqueKey(primShape,size,(byte)lod, convex);
  991. lock (m_uniqueMeshes)
  992. {
  993. m_uniqueMeshes.TryGetValue(key, out mesh);
  994. if (mesh != null)
  995. {
  996. mesh.RefCount++;
  997. return mesh;
  998. }
  999. // try to find a identical mesh on meshs recently released
  1000. lock (m_uniqueReleasedMeshes)
  1001. {
  1002. m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
  1003. if (mesh != null)
  1004. {
  1005. m_uniqueReleasedMeshes.Remove(key);
  1006. try
  1007. {
  1008. m_uniqueMeshes.Add(key, mesh);
  1009. }
  1010. catch { }
  1011. mesh.RefCount = 1;
  1012. return mesh;
  1013. }
  1014. }
  1015. }
  1016. Mesh UnitMesh = null;
  1017. AMeshKey unitKey = GetMeshUniqueKey(primShape, m_MeshUnitSize, (byte)lod, convex);
  1018. lock (m_uniqueReleasedMeshes)
  1019. {
  1020. m_uniqueReleasedMeshes.TryGetValue(unitKey, out UnitMesh);
  1021. if (UnitMesh != null)
  1022. {
  1023. UnitMesh.RefCount = 1;
  1024. }
  1025. }
  1026. if (UnitMesh == null && primShape.SculptEntry && doMeshFileCache)
  1027. UnitMesh = GetFromFileCache(unitKey);
  1028. if (UnitMesh == null)
  1029. {
  1030. UnitMesh = CreateMeshFromPrimMesher(primName, primShape, lod, convex);
  1031. if (UnitMesh == null)
  1032. return null;
  1033. UnitMesh.DumpRaw(baseDir, unitKey.ToString(), "Z");
  1034. if (forOde)
  1035. {
  1036. // force pinned mem allocation
  1037. UnitMesh.PrepForOde();
  1038. }
  1039. else
  1040. UnitMesh.TrimExcess();
  1041. UnitMesh.Key = unitKey;
  1042. UnitMesh.RefCount = 1;
  1043. if (doMeshFileCache && primShape.SculptEntry)
  1044. StoreToFileCache(unitKey, UnitMesh);
  1045. lock (m_uniqueReleasedMeshes)
  1046. {
  1047. try
  1048. {
  1049. m_uniqueReleasedMeshes.Add(unitKey, UnitMesh);
  1050. }
  1051. catch { }
  1052. }
  1053. }
  1054. mesh = UnitMesh.Scale(size);
  1055. mesh.Key = key;
  1056. mesh.RefCount = 1;
  1057. lock (m_uniqueMeshes)
  1058. {
  1059. try
  1060. {
  1061. m_uniqueMeshes.Add(key, mesh);
  1062. }
  1063. catch { }
  1064. }
  1065. return mesh;
  1066. }
  1067. public void ReleaseMesh(IMesh imesh)
  1068. {
  1069. if (imesh == null)
  1070. return;
  1071. Mesh mesh = (Mesh)imesh;
  1072. lock (m_uniqueMeshes)
  1073. {
  1074. int curRefCount = mesh.RefCount;
  1075. curRefCount--;
  1076. if (curRefCount > 0)
  1077. {
  1078. mesh.RefCount = curRefCount;
  1079. return;
  1080. }
  1081. mesh.RefCount = 0;
  1082. m_uniqueMeshes.Remove(mesh.Key);
  1083. lock (m_uniqueReleasedMeshes)
  1084. {
  1085. try
  1086. {
  1087. m_uniqueReleasedMeshes.Add(mesh.Key, mesh);
  1088. }
  1089. catch { }
  1090. }
  1091. }
  1092. }
  1093. public void ExpireReleaseMeshs()
  1094. {
  1095. if (m_uniqueReleasedMeshes.Count == 0)
  1096. return;
  1097. List<Mesh> meshstodelete = new List<Mesh>();
  1098. int refcntr;
  1099. lock (m_uniqueReleasedMeshes)
  1100. {
  1101. foreach (Mesh m in m_uniqueReleasedMeshes.Values)
  1102. {
  1103. refcntr = m.RefCount;
  1104. refcntr--;
  1105. if (refcntr > -6)
  1106. m.RefCount = refcntr;
  1107. else
  1108. meshstodelete.Add(m);
  1109. }
  1110. foreach (Mesh m in meshstodelete)
  1111. {
  1112. m_uniqueReleasedMeshes.Remove(m.Key);
  1113. m.releaseBuildingMeshData();
  1114. m.releasePinned();
  1115. }
  1116. }
  1117. }
  1118. public void FileNames(AMeshKey key, out string dir, out string fullFileName)
  1119. {
  1120. string id = key.ToString();
  1121. string init = id.Substring(0, 1);
  1122. dir = System.IO.Path.Combine(cachePath, init);
  1123. fullFileName = System.IO.Path.Combine(dir, id);
  1124. }
  1125. public string FullFileName(AMeshKey key)
  1126. {
  1127. string id = key.ToString();
  1128. string init = id.Substring(0,1);
  1129. id = System.IO.Path.Combine(init, id);
  1130. id = System.IO.Path.Combine(cachePath, id);
  1131. return id;
  1132. }
  1133. private Mesh GetFromFileCache(AMeshKey key)
  1134. {
  1135. Mesh mesh = null;
  1136. string filename = FullFileName(key);
  1137. bool ok = true;
  1138. lock (diskLock)
  1139. {
  1140. if (File.Exists(filename))
  1141. {
  1142. try
  1143. {
  1144. using(FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  1145. {
  1146. // BinaryFormatter bformatter = new BinaryFormatter();
  1147. mesh = Mesh.FromStream(stream,key);
  1148. }
  1149. }
  1150. catch (Exception e)
  1151. {
  1152. ok = false;
  1153. m_log.ErrorFormat(
  1154. "[MESH CACHE]: Failed to get file {0}. Exception {1} {2}",
  1155. filename, e.Message, e.StackTrace);
  1156. }
  1157. try
  1158. {
  1159. if (mesh == null || !ok)
  1160. File.Delete(filename);
  1161. else
  1162. File.SetLastAccessTimeUtc(filename, DateTime.UtcNow);
  1163. }
  1164. catch
  1165. {
  1166. }
  1167. }
  1168. }
  1169. return mesh;
  1170. }
  1171. private void StoreToFileCache(AMeshKey key, Mesh mesh)
  1172. {
  1173. bool ok = false;
  1174. // Make sure the target cache directory exists
  1175. string dir = String.Empty;
  1176. string filename = String.Empty;
  1177. FileNames(key, out dir, out filename);
  1178. lock (diskLock)
  1179. {
  1180. Stream stream = null;
  1181. try
  1182. {
  1183. if (!Directory.Exists(dir))
  1184. {
  1185. Directory.CreateDirectory(dir);
  1186. }
  1187. stream = File.Open(filename, FileMode.Create);
  1188. ok = mesh.ToStream(stream);
  1189. }
  1190. catch (IOException e)
  1191. {
  1192. m_log.ErrorFormat(
  1193. "[MESH CACHE]: Failed to write file {0}. Exception {1} {2}.",
  1194. filename, e.Message, e.StackTrace);
  1195. ok = false;
  1196. }
  1197. finally
  1198. {
  1199. if(stream != null)
  1200. stream.Dispose();
  1201. }
  1202. if (!ok && File.Exists(filename))
  1203. {
  1204. try
  1205. {
  1206. File.Delete(filename);
  1207. }
  1208. catch (IOException)
  1209. {
  1210. m_log.ErrorFormat(
  1211. "[MESH CACHE]: Failed to delete file {0}",filename);
  1212. }
  1213. }
  1214. }
  1215. }
  1216. private static DateTime lastExpireTime = DateTime.MinValue;
  1217. public void ExpireFileCache()
  1218. {
  1219. if (!doCacheExpire)
  1220. return;
  1221. lock (diskLock)
  1222. {
  1223. try
  1224. {
  1225. DateTime now = DateTime.UtcNow;
  1226. if(now.Subtract(lastExpireTime).TotalMinutes < 10.0)
  1227. return;
  1228. lastExpireTime = now;
  1229. string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
  1230. if (File.Exists(controlfile))
  1231. {
  1232. int ndeleted = 0;
  1233. int totalfiles = 0;
  1234. int ndirs = 0;
  1235. DateTime OlderTime = File.GetLastAccessTimeUtc(controlfile) - CacheExpire;
  1236. File.SetLastAccessTimeUtc(controlfile, now);
  1237. foreach (string dir in Directory.GetDirectories(cachePath))
  1238. {
  1239. try
  1240. {
  1241. foreach (string file in Directory.GetFiles(dir))
  1242. {
  1243. try
  1244. {
  1245. if (File.GetLastAccessTimeUtc(file) < OlderTime)
  1246. {
  1247. File.Delete(file);
  1248. ndeleted++;
  1249. }
  1250. }
  1251. catch { }
  1252. totalfiles++;
  1253. }
  1254. }
  1255. catch { }
  1256. ndirs++;
  1257. }
  1258. if (ndeleted == 0)
  1259. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, no expires",
  1260. totalfiles,ndirs);
  1261. else
  1262. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, expired {2} files accessed before {3}",
  1263. totalfiles,ndirs, ndeleted, OlderTime.ToString());
  1264. }
  1265. else
  1266. {
  1267. m_log.Info("[MESH CACHE]: Expire delayed to next startup");
  1268. FileStream fs = File.Create(controlfile,4096,FileOptions.WriteThrough);
  1269. fs.Close();
  1270. }
  1271. }
  1272. catch { }
  1273. }
  1274. }
  1275. public bool checkCache()
  1276. {
  1277. string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
  1278. lock (diskLock)
  1279. {
  1280. try
  1281. {
  1282. if (!Directory.Exists(cachePath))
  1283. {
  1284. Directory.CreateDirectory(cachePath);
  1285. Thread.Sleep(100);
  1286. FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
  1287. fs.Close();
  1288. return true;
  1289. }
  1290. }
  1291. catch
  1292. {
  1293. doMeshFileCache = false;
  1294. doCacheExpire = false;
  1295. return false;
  1296. }
  1297. finally {}
  1298. if (File.Exists(controlfile))
  1299. return true;
  1300. try
  1301. {
  1302. Directory.Delete(cachePath, true);
  1303. while(Directory.Exists(cachePath))
  1304. Thread.Sleep(100);
  1305. }
  1306. catch(Exception e)
  1307. {
  1308. m_log.Error("[MESH CACHE]: failed to delete old version of the cache: " + e.Message);
  1309. doMeshFileCache = false;
  1310. doCacheExpire = false;
  1311. return false;
  1312. }
  1313. finally {}
  1314. try
  1315. {
  1316. Directory.CreateDirectory(cachePath);
  1317. while(!Directory.Exists(cachePath))
  1318. Thread.Sleep(100);
  1319. }
  1320. catch(Exception e)
  1321. {
  1322. m_log.Error("[MESH CACHE]: failed to create new cache folder: " + e.Message);
  1323. doMeshFileCache = false;
  1324. doCacheExpire = false;
  1325. return false;
  1326. }
  1327. finally {}
  1328. try
  1329. {
  1330. FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
  1331. fs.Close();
  1332. }
  1333. catch(Exception e)
  1334. {
  1335. m_log.Error("[MESH CACHE]: failed to create new control file: " + e.Message);
  1336. doMeshFileCache = false;
  1337. doCacheExpire = false;
  1338. return false;
  1339. }
  1340. finally {}
  1341. return true;
  1342. }
  1343. }
  1344. public bool CreateBoundingHull(List<Coord> inputVertices, out List<Coord> convexcoords, out List<Face> newfaces)
  1345. {
  1346. convexcoords = null;
  1347. newfaces = null;
  1348. HullDesc desc = new HullDesc();
  1349. HullResult result = new HullResult();
  1350. int nInputVerts = inputVertices.Count;
  1351. int i;
  1352. List<float3> vs = new List<float3>(nInputVerts);
  1353. float3 f3;
  1354. //useless copy
  1355. for(i = 0 ; i < nInputVerts; i++)
  1356. {
  1357. f3 = new float3(inputVertices[i].X, inputVertices[i].Y, inputVertices[i].Z);
  1358. vs.Add(f3);
  1359. }
  1360. desc.Vertices = vs;
  1361. desc.Flags = HullFlag.QF_TRIANGLES;
  1362. desc.MaxVertices = 256;
  1363. try
  1364. {
  1365. HullError ret = HullUtils.CreateConvexHull(desc, ref result);
  1366. if (ret != HullError.QE_OK)
  1367. return false;
  1368. int nverts = result.OutputVertices.Count;
  1369. int nindx = result.Indices.Count;
  1370. if(nverts < 3 || nindx< 3)
  1371. return false;
  1372. if(nindx % 3 != 0)
  1373. return false;
  1374. convexcoords = new List<Coord>(nverts);
  1375. Coord c;
  1376. vs = result.OutputVertices;
  1377. for(i = 0 ; i < nverts; i++)
  1378. {
  1379. c = new Coord(vs[i].x, vs[i].y, vs[i].z);
  1380. convexcoords.Add(c);
  1381. }
  1382. newfaces = new List<Face>(nindx / 3);
  1383. List<int> indxs = result.Indices;
  1384. int k, l, m;
  1385. Face f;
  1386. for(i = 0 ; i < nindx;)
  1387. {
  1388. k = indxs[i++];
  1389. l = indxs[i++];
  1390. m = indxs[i++];
  1391. if(k > nInputVerts)
  1392. continue;
  1393. if(l > nInputVerts)
  1394. continue;
  1395. if(m > nInputVerts)
  1396. continue;
  1397. f = new Face(k,l,m);
  1398. newfaces.Add(f);
  1399. }
  1400. }
  1401. catch
  1402. {
  1403. return false;
  1404. }
  1405. return true;
  1406. }
  1407. }
  1408. }