Meshmerizer.cs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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. public void ExpireFileCache()
  1217. {
  1218. if (!doCacheExpire)
  1219. return;
  1220. string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
  1221. lock (diskLock)
  1222. {
  1223. try
  1224. {
  1225. if (File.Exists(controlfile))
  1226. {
  1227. int ndeleted = 0;
  1228. int totalfiles = 0;
  1229. int ndirs = 0;
  1230. DateTime OlderTime = File.GetLastAccessTimeUtc(controlfile) - CacheExpire;
  1231. File.SetLastAccessTimeUtc(controlfile, DateTime.UtcNow);
  1232. foreach (string dir in Directory.GetDirectories(cachePath))
  1233. {
  1234. try
  1235. {
  1236. foreach (string file in Directory.GetFiles(dir))
  1237. {
  1238. try
  1239. {
  1240. if (File.GetLastAccessTimeUtc(file) < OlderTime)
  1241. {
  1242. File.Delete(file);
  1243. ndeleted++;
  1244. }
  1245. }
  1246. catch { }
  1247. totalfiles++;
  1248. }
  1249. }
  1250. catch { }
  1251. ndirs++;
  1252. }
  1253. if (ndeleted == 0)
  1254. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, no expires",
  1255. totalfiles,ndirs);
  1256. else
  1257. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, expired {2} files accessed before {3}",
  1258. totalfiles,ndirs, ndeleted, OlderTime.ToString());
  1259. }
  1260. else
  1261. {
  1262. m_log.Info("[MESH CACHE]: Expire delayed to next startup");
  1263. FileStream fs = File.Create(controlfile,4096,FileOptions.WriteThrough);
  1264. fs.Close();
  1265. }
  1266. }
  1267. catch { }
  1268. }
  1269. }
  1270. public bool checkCache()
  1271. {
  1272. string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
  1273. lock (diskLock)
  1274. {
  1275. try
  1276. {
  1277. if (!Directory.Exists(cachePath))
  1278. {
  1279. Directory.CreateDirectory(cachePath);
  1280. Thread.Sleep(100);
  1281. FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
  1282. fs.Close();
  1283. return true;
  1284. }
  1285. }
  1286. catch
  1287. {
  1288. doMeshFileCache = false;
  1289. doCacheExpire = false;
  1290. return false;
  1291. }
  1292. finally {}
  1293. if (File.Exists(controlfile))
  1294. return true;
  1295. try
  1296. {
  1297. Directory.Delete(cachePath, true);
  1298. while(Directory.Exists(cachePath))
  1299. Thread.Sleep(100);
  1300. }
  1301. catch(Exception e)
  1302. {
  1303. m_log.Error("[MESH CACHE]: failed to delete old version of the cache: " + e.Message);
  1304. doMeshFileCache = false;
  1305. doCacheExpire = false;
  1306. return false;
  1307. }
  1308. finally {}
  1309. try
  1310. {
  1311. Directory.CreateDirectory(cachePath);
  1312. while(!Directory.Exists(cachePath))
  1313. Thread.Sleep(100);
  1314. }
  1315. catch(Exception e)
  1316. {
  1317. m_log.Error("[MESH CACHE]: failed to create new cache folder: " + e.Message);
  1318. doMeshFileCache = false;
  1319. doCacheExpire = false;
  1320. return false;
  1321. }
  1322. finally {}
  1323. try
  1324. {
  1325. FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
  1326. fs.Close();
  1327. }
  1328. catch(Exception e)
  1329. {
  1330. m_log.Error("[MESH CACHE]: failed to create new control file: " + e.Message);
  1331. doMeshFileCache = false;
  1332. doCacheExpire = false;
  1333. return false;
  1334. }
  1335. finally {}
  1336. return true;
  1337. }
  1338. }
  1339. public bool CreateBoundingHull(List<Coord> inputVertices, out List<Coord> convexcoords, out List<Face> newfaces)
  1340. {
  1341. convexcoords = null;
  1342. newfaces = null;
  1343. HullDesc desc = new HullDesc();
  1344. HullResult result = new HullResult();
  1345. int nInputVerts = inputVertices.Count;
  1346. int i;
  1347. List<float3> vs = new List<float3>(nInputVerts);
  1348. float3 f3;
  1349. //useless copy
  1350. for(i = 0 ; i < nInputVerts; i++)
  1351. {
  1352. f3 = new float3(inputVertices[i].X, inputVertices[i].Y, inputVertices[i].Z);
  1353. vs.Add(f3);
  1354. }
  1355. desc.Vertices = vs;
  1356. desc.Flags = HullFlag.QF_TRIANGLES;
  1357. desc.MaxVertices = 256;
  1358. try
  1359. {
  1360. HullError ret = HullUtils.CreateConvexHull(desc, ref result);
  1361. if (ret != HullError.QE_OK)
  1362. return false;
  1363. int nverts = result.OutputVertices.Count;
  1364. int nindx = result.Indices.Count;
  1365. if(nverts < 3 || nindx< 3)
  1366. return false;
  1367. if(nindx % 3 != 0)
  1368. return false;
  1369. convexcoords = new List<Coord>(nverts);
  1370. Coord c;
  1371. vs = result.OutputVertices;
  1372. for(i = 0 ; i < nverts; i++)
  1373. {
  1374. c = new Coord(vs[i].x, vs[i].y, vs[i].z);
  1375. convexcoords.Add(c);
  1376. }
  1377. newfaces = new List<Face>(nindx / 3);
  1378. List<int> indxs = result.Indices;
  1379. int k, l, m;
  1380. Face f;
  1381. for(i = 0 ; i < nindx;)
  1382. {
  1383. k = indxs[i++];
  1384. l = indxs[i++];
  1385. m = indxs[i++];
  1386. if(k > nInputVerts)
  1387. continue;
  1388. if(l > nInputVerts)
  1389. continue;
  1390. if(m > nInputVerts)
  1391. continue;
  1392. f = new Face(k,l,m);
  1393. newfaces.Add(f);
  1394. }
  1395. }
  1396. catch
  1397. {
  1398. return false;
  1399. }
  1400. return true;
  1401. }
  1402. }
  1403. }