1
0

Meshmerizer.cs 60 KB

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