Meshmerizer.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.Physics.Manager;
  32. using OpenMetaverse;
  33. using OpenMetaverse.Imaging;
  34. using System.Drawing;
  35. using System.Drawing.Imaging;
  36. using PrimMesher;
  37. using log4net;
  38. using System.Reflection;
  39. using System.IO;
  40. namespace OpenSim.Region.Physics.Meshing
  41. {
  42. public class MeshmerizerPlugin : IMeshingPlugin
  43. {
  44. public MeshmerizerPlugin()
  45. {
  46. }
  47. public string GetName()
  48. {
  49. return "Meshmerizer";
  50. }
  51. public IMesher GetMesher()
  52. {
  53. return new Meshmerizer();
  54. }
  55. }
  56. public class Meshmerizer : IMesher
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. //private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  60. // Setting baseDir to a path will enable the dumping of raw files
  61. // raw files can be imported by blender so a visual inspection of the results can be done
  62. #if SPAM
  63. const string baseDir = "rawFiles";
  64. #else
  65. private const string baseDir = null; //"rawFiles";
  66. #endif
  67. private bool cacheSculptMaps = true;
  68. private string decodedScultMapPath = "j2kDecodeCache";
  69. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  70. private Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
  71. public Meshmerizer()
  72. {
  73. try
  74. {
  75. if (!Directory.Exists(decodedScultMapPath))
  76. Directory.CreateDirectory(decodedScultMapPath);
  77. }
  78. catch (Exception e)
  79. {
  80. m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedScultMapPath, e.Message);
  81. }
  82. }
  83. /// <summary>
  84. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  85. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  86. /// for some reason
  87. /// </summary>
  88. /// <param name="minX"></param>
  89. /// <param name="maxX"></param>
  90. /// <param name="minY"></param>
  91. /// <param name="maxY"></param>
  92. /// <param name="minZ"></param>
  93. /// <param name="maxZ"></param>
  94. /// <returns></returns>
  95. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  96. {
  97. Mesh box = new Mesh();
  98. List<Vertex> vertices = new List<Vertex>();
  99. // bottom
  100. vertices.Add(new Vertex(minX, maxY, minZ));
  101. vertices.Add(new Vertex(maxX, maxY, minZ));
  102. vertices.Add(new Vertex(maxX, minY, minZ));
  103. vertices.Add(new Vertex(minX, minY, minZ));
  104. box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
  105. box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
  106. // top
  107. vertices.Add(new Vertex(maxX, maxY, maxZ));
  108. vertices.Add(new Vertex(minX, maxY, maxZ));
  109. vertices.Add(new Vertex(minX, minY, maxZ));
  110. vertices.Add(new Vertex(maxX, minY, maxZ));
  111. box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
  112. box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
  113. // sides
  114. box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
  115. box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
  116. box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
  117. box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
  118. box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
  119. box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
  120. box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
  121. box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
  122. return box;
  123. }
  124. /// <summary>
  125. /// Creates a simple bounding box mesh for a complex input mesh
  126. /// </summary>
  127. /// <param name="meshIn"></param>
  128. /// <returns></returns>
  129. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  130. {
  131. float minX = float.MaxValue;
  132. float maxX = float.MinValue;
  133. float minY = float.MaxValue;
  134. float maxY = float.MinValue;
  135. float minZ = float.MaxValue;
  136. float maxZ = float.MinValue;
  137. foreach (Vertex v in meshIn.getVertexList())
  138. {
  139. if (v != null)
  140. {
  141. if (v.X < minX) minX = v.X;
  142. if (v.Y < minY) minY = v.Y;
  143. if (v.Z < minZ) minZ = v.Z;
  144. if (v.X > maxX) maxX = v.X;
  145. if (v.Y > maxY) maxY = v.Y;
  146. if (v.Z > maxZ) maxZ = v.Z;
  147. }
  148. }
  149. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  150. }
  151. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  152. {
  153. m_log.Error(message);
  154. m_log.Error("\nPrim Name: " + primName);
  155. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  156. }
  157. private ulong GetMeshKey(PrimitiveBaseShape pbs, PhysicsVector size, float lod)
  158. {
  159. ulong hash = 5381;
  160. hash = djb2(hash, pbs.PathCurve);
  161. hash = djb2(hash, (byte)((byte)pbs.HollowShape | (byte)pbs.ProfileShape));
  162. hash = djb2(hash, pbs.PathBegin);
  163. hash = djb2(hash, pbs.PathEnd);
  164. hash = djb2(hash, pbs.PathScaleX);
  165. hash = djb2(hash, pbs.PathScaleY);
  166. hash = djb2(hash, pbs.PathShearX);
  167. hash = djb2(hash, pbs.PathShearY);
  168. hash = djb2(hash, (byte)pbs.PathTwist);
  169. hash = djb2(hash, (byte)pbs.PathTwistBegin);
  170. hash = djb2(hash, (byte)pbs.PathRadiusOffset);
  171. hash = djb2(hash, (byte)pbs.PathTaperX);
  172. hash = djb2(hash, (byte)pbs.PathTaperY);
  173. hash = djb2(hash, pbs.PathRevolutions);
  174. hash = djb2(hash, (byte)pbs.PathSkew);
  175. hash = djb2(hash, pbs.ProfileBegin);
  176. hash = djb2(hash, pbs.ProfileEnd);
  177. hash = djb2(hash, pbs.ProfileHollow);
  178. // TODO: Separate scale out from the primitive shape data (after
  179. // scaling is supported at the physics engine level)
  180. byte[] scaleBytes = size.GetBytes();
  181. for (int i = 0; i < scaleBytes.Length; i++)
  182. hash = djb2(hash, scaleBytes[i]);
  183. // Include LOD in hash, accounting for endianness
  184. byte[] lodBytes = new byte[4];
  185. Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
  186. if (!BitConverter.IsLittleEndian)
  187. {
  188. Array.Reverse(lodBytes, 0, 4);
  189. }
  190. for (int i = 0; i < lodBytes.Length; i++)
  191. hash = djb2(hash, lodBytes[i]);
  192. // include sculpt UUID
  193. if (pbs.SculptEntry)
  194. {
  195. scaleBytes = pbs.SculptTexture.GetBytes();
  196. for (int i = 0; i < scaleBytes.Length; i++)
  197. hash = djb2(hash, scaleBytes[i]);
  198. }
  199. return hash;
  200. }
  201. private ulong djb2(ulong hash, byte c)
  202. {
  203. return ((hash << 5) + hash) + (ulong)c;
  204. }
  205. private ulong djb2(ulong hash, ushort c)
  206. {
  207. hash = ((hash << 5) + hash) + (ulong)((byte)c);
  208. return ((hash << 5) + hash) + (ulong)(c >> 8);
  209. }
  210. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod)
  211. {
  212. PrimMesh primMesh;
  213. PrimMesher.SculptMesh sculptMesh;
  214. List<Coord> coords;
  215. List<Face> faces;
  216. Image idata = null;
  217. string decodedSculptFileName = "";
  218. if (primShape.SculptEntry)
  219. {
  220. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  221. {
  222. decodedSculptFileName = System.IO.Path.Combine(decodedScultMapPath, "smap_" + primShape.SculptTexture.ToString());
  223. try
  224. {
  225. if (File.Exists(decodedSculptFileName))
  226. {
  227. idata = Image.FromFile(decodedSculptFileName);
  228. }
  229. }
  230. catch (Exception e)
  231. {
  232. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  233. }
  234. //if (idata != null)
  235. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  236. }
  237. if (idata == null)
  238. {
  239. if (primShape.SculptData.Length == 0)
  240. return null;
  241. try
  242. {
  243. ManagedImage managedImage; // we never use this
  244. OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage, out idata);
  245. // Remove the reference to the encoded JPEG2000 data so it can be GCed
  246. primShape.SculptData = Utils.EmptyBytes;
  247. if (cacheSculptMaps)
  248. {
  249. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  250. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  251. }
  252. }
  253. catch (DllNotFoundException)
  254. {
  255. 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!");
  256. return null;
  257. }
  258. catch (IndexOutOfRangeException)
  259. {
  260. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  261. return null;
  262. }
  263. catch (Exception)
  264. {
  265. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed!");
  266. return null;
  267. }
  268. }
  269. PrimMesher.SculptMesh.SculptType sculptType;
  270. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  271. {
  272. case OpenMetaverse.SculptType.Cylinder:
  273. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  274. break;
  275. case OpenMetaverse.SculptType.Plane:
  276. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  277. break;
  278. case OpenMetaverse.SculptType.Torus:
  279. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  280. break;
  281. case OpenMetaverse.SculptType.Sphere:
  282. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  283. break;
  284. default:
  285. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  286. break;
  287. }
  288. bool mirror = ((primShape.SculptType & 128) != 0);
  289. bool invert = ((primShape.SculptType & 64) != 0);
  290. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  291. idata.Dispose();
  292. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  293. sculptMesh.Scale(size.X, size.Y, size.Z);
  294. coords = sculptMesh.coords;
  295. faces = sculptMesh.faces;
  296. }
  297. else
  298. {
  299. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  300. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  301. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  302. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  303. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  304. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  305. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  306. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  307. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  308. if (profileHollow > 0.95f)
  309. profileHollow = 0.95f;
  310. int sides = 4;
  311. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  312. sides = 3;
  313. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  314. sides = 24;
  315. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  316. { // half circle, prim is a sphere
  317. sides = 24;
  318. profileBegin = 0.5f * profileBegin + 0.5f;
  319. profileEnd = 0.5f * profileEnd + 0.5f;
  320. }
  321. int hollowSides = sides;
  322. if (primShape.HollowShape == HollowShape.Circle)
  323. hollowSides = 24;
  324. else if (primShape.HollowShape == HollowShape.Square)
  325. hollowSides = 4;
  326. else if (primShape.HollowShape == HollowShape.Triangle)
  327. hollowSides = 3;
  328. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  329. if (primMesh.errorMessage != null)
  330. if (primMesh.errorMessage.Length > 0)
  331. m_log.Error("[ERROR] " + primMesh.errorMessage);
  332. primMesh.topShearX = pathShearX;
  333. primMesh.topShearY = pathShearY;
  334. primMesh.pathCutBegin = pathBegin;
  335. primMesh.pathCutEnd = pathEnd;
  336. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  337. {
  338. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  339. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  340. primMesh.taperX = pathScaleX;
  341. primMesh.taperY = pathScaleY;
  342. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  343. {
  344. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  345. if (profileBegin < 0.0f) profileBegin = 0.0f;
  346. if (profileEnd > 1.0f) profileEnd = 1.0f;
  347. }
  348. #if SPAM
  349. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  350. #endif
  351. try
  352. {
  353. primMesh.ExtrudeLinear();
  354. }
  355. catch (Exception ex)
  356. {
  357. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  358. return null;
  359. }
  360. }
  361. else
  362. {
  363. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  364. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  365. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  366. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  367. primMesh.skew = 0.01f * primShape.PathSkew;
  368. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  369. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  370. primMesh.taperX = primShape.PathTaperX * 0.01f;
  371. primMesh.taperY = primShape.PathTaperY * 0.01f;
  372. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  373. {
  374. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  375. if (profileBegin < 0.0f) profileBegin = 0.0f;
  376. if (profileEnd > 1.0f) profileEnd = 1.0f;
  377. }
  378. #if SPAM
  379. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  380. #endif
  381. try
  382. {
  383. primMesh.ExtrudeCircular();
  384. }
  385. catch (Exception ex)
  386. {
  387. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  388. return null;
  389. }
  390. }
  391. primMesh.DumpRaw(baseDir, primName, "primMesh");
  392. primMesh.Scale(size.X, size.Y, size.Z);
  393. coords = primMesh.coords;
  394. faces = primMesh.faces;
  395. }
  396. int numCoords = coords.Count;
  397. int numFaces = faces.Count;
  398. // Create the list of vertices
  399. List<Vertex> vertices = new List<Vertex>();
  400. for (int i = 0; i < numCoords; i++)
  401. {
  402. Coord c = coords[i];
  403. vertices.Add(new Vertex(c.X, c.Y, c.Z));
  404. }
  405. Mesh mesh = new Mesh();
  406. // Add the corresponding triangles to the mesh
  407. for (int i = 0; i < numFaces; i++)
  408. {
  409. Face f = faces[i];
  410. mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
  411. }
  412. return mesh;
  413. }
  414. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod)
  415. {
  416. return CreateMesh(primName, primShape, size, lod, false);
  417. }
  418. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical)
  419. {
  420. Mesh mesh = null;
  421. ulong key = 0;
  422. // If this mesh has been created already, return it instead of creating another copy
  423. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  424. key = GetMeshKey(primShape, size, lod);
  425. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  426. return mesh;
  427. if (size.X < 0.01f) size.X = 0.01f;
  428. if (size.Y < 0.01f) size.Y = 0.01f;
  429. if (size.Z < 0.01f) size.Z = 0.01f;
  430. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  431. if (mesh != null)
  432. {
  433. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  434. {
  435. #if SPAM
  436. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  437. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  438. #endif
  439. mesh = CreateBoundingBoxMesh(mesh);
  440. mesh.DumpRaw(baseDir, primName, "Z extruded");
  441. }
  442. // trim the vertex and triangle lists to free up memory
  443. mesh.TrimExcess();
  444. m_uniqueMeshes.Add(key, mesh);
  445. }
  446. return mesh;
  447. }
  448. }
  449. }