Meshmerizer.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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 System.Reflection;
  31. using System.IO;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework.Scenes;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.PhysicsModules.SharedBase;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. using System.Drawing;
  39. using System.Drawing.Imaging;
  40. using System.IO.Compression;
  41. using PrimMesher;
  42. using log4net;
  43. using Nini.Config;
  44. using Mono.Addins;
  45. namespace OpenSim.Region.PhysicsModule.Meshing
  46. {
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Meshmerizer")]
  48. public class Meshmerizer : IMesher, INonSharedRegionModule
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. private static string LogHeader = "[MESH]";
  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. #if SPAM
  55. const string baseDir = "rawFiles";
  56. #else
  57. private const string baseDir = null; //"rawFiles";
  58. #endif
  59. private bool m_Enabled = false;
  60. // If 'true', lots of DEBUG logging of asset parsing details
  61. private bool debugDetail = false;
  62. private bool cacheSculptMaps = true;
  63. private string decodedSculptMapPath = null;
  64. private bool useMeshiesPhysicsMesh = true;
  65. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  66. private List<List<Vector3>> mConvexHulls = null;
  67. private List<Vector3> mBoundingHull = null;
  68. // Mesh cache. Static so it can be shared across instances of this class
  69. private static Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
  70. #region INonSharedRegionModule
  71. public string Name
  72. {
  73. get { return "Meshmerizer"; }
  74. }
  75. public Type ReplaceableInterface
  76. {
  77. get { return null; }
  78. }
  79. public void Initialise(IConfigSource source)
  80. {
  81. IConfig config = source.Configs["Startup"];
  82. if (config != null)
  83. {
  84. string mesher = config.GetString("meshing", string.Empty);
  85. if (mesher == Name)
  86. {
  87. m_Enabled = true;
  88. IConfig mesh_config = source.Configs["Mesh"];
  89. decodedSculptMapPath = config.GetString("DecodedSculptMapPath", "j2kDecodeCache");
  90. cacheSculptMaps = config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
  91. if (mesh_config != null)
  92. {
  93. useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
  94. debugDetail = mesh_config.GetBoolean("LogMeshDetails", debugDetail);
  95. }
  96. try
  97. {
  98. if (!Directory.Exists(decodedSculptMapPath))
  99. Directory.CreateDirectory(decodedSculptMapPath);
  100. }
  101. catch (Exception e)
  102. {
  103. m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath, e.Message);
  104. }
  105. }
  106. }
  107. }
  108. public void Close()
  109. {
  110. }
  111. public void AddRegion(Scene scene)
  112. {
  113. if (!m_Enabled)
  114. return;
  115. scene.RegisterModuleInterface<IMesher>(this);
  116. }
  117. public void RemoveRegion(Scene scene)
  118. {
  119. if (!m_Enabled)
  120. return;
  121. scene.UnregisterModuleInterface<IMesher>(this);
  122. }
  123. public void RegionLoaded(Scene scene)
  124. {
  125. if (!m_Enabled)
  126. return;
  127. }
  128. #endregion
  129. /// <summary>
  130. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  131. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  132. /// for some reason
  133. /// </summary>
  134. /// <param name="minX"></param>
  135. /// <param name="maxX"></param>
  136. /// <param name="minY"></param>
  137. /// <param name="maxY"></param>
  138. /// <param name="minZ"></param>
  139. /// <param name="maxZ"></param>
  140. /// <returns></returns>
  141. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  142. {
  143. Mesh box = new Mesh();
  144. List<Vertex> vertices = new List<Vertex>();
  145. // bottom
  146. vertices.Add(new Vertex(minX, maxY, minZ));
  147. vertices.Add(new Vertex(maxX, maxY, minZ));
  148. vertices.Add(new Vertex(maxX, minY, minZ));
  149. vertices.Add(new Vertex(minX, minY, minZ));
  150. box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
  151. box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
  152. // top
  153. vertices.Add(new Vertex(maxX, maxY, maxZ));
  154. vertices.Add(new Vertex(minX, maxY, maxZ));
  155. vertices.Add(new Vertex(minX, minY, maxZ));
  156. vertices.Add(new Vertex(maxX, minY, maxZ));
  157. box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
  158. box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
  159. // sides
  160. box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
  161. box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
  162. box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
  163. box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
  164. box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
  165. box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
  166. box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
  167. box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
  168. return box;
  169. }
  170. /// <summary>
  171. /// Creates a simple bounding box mesh for a complex input mesh
  172. /// </summary>
  173. /// <param name="meshIn"></param>
  174. /// <returns></returns>
  175. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  176. {
  177. float minX = float.MaxValue;
  178. float maxX = float.MinValue;
  179. float minY = float.MaxValue;
  180. float maxY = float.MinValue;
  181. float minZ = float.MaxValue;
  182. float maxZ = float.MinValue;
  183. foreach (Vector3 v in meshIn.getVertexList())
  184. {
  185. if (v.X < minX) minX = v.X;
  186. if (v.Y < minY) minY = v.Y;
  187. if (v.Z < minZ) minZ = v.Z;
  188. if (v.X > maxX) maxX = v.X;
  189. if (v.Y > maxY) maxY = v.Y;
  190. if (v.Z > maxZ) maxZ = v.Z;
  191. }
  192. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  193. }
  194. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  195. {
  196. m_log.Error(message);
  197. m_log.Error("\nPrim Name: " + primName);
  198. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  199. }
  200. /// <summary>
  201. /// Add a submesh to an existing list of coords and faces.
  202. /// </summary>
  203. /// <param name="subMeshData"></param>
  204. /// <param name="size">Size of entire object</param>
  205. /// <param name="coords"></param>
  206. /// <param name="faces"></param>
  207. private void AddSubMesh(OSDMap subMeshData, Vector3 size, List<Coord> coords, List<Face> faces)
  208. {
  209. // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
  210. // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
  211. // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
  212. // geometry for this submesh.
  213. if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
  214. return;
  215. OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
  216. OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
  217. ushort faceIndexOffset = (ushort)coords.Count;
  218. byte[] posBytes = subMeshData["Position"].AsBinary();
  219. for (int i = 0; i < posBytes.Length; i += 6)
  220. {
  221. ushort uX = Utils.BytesToUInt16(posBytes, i);
  222. ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
  223. ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
  224. Coord c = new Coord(
  225. Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X,
  226. Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y,
  227. Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z);
  228. coords.Add(c);
  229. }
  230. byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
  231. for (int i = 0; i < triangleBytes.Length; i += 6)
  232. {
  233. ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
  234. ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
  235. ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
  236. Face f = new Face(v1, v2, v3);
  237. faces.Add(f);
  238. }
  239. }
  240. /// <summary>
  241. /// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
  242. /// </summary>
  243. /// <param name="primName"></param>
  244. /// <param name="primShape"></param>
  245. /// <param name="size"></param>
  246. /// <param name="lod"></param>
  247. /// <returns></returns>
  248. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  249. {
  250. // m_log.DebugFormat(
  251. // "[MESH]: Creating physics proxy for {0}, shape {1}",
  252. // primName, (OpenMetaverse.SculptType)primShape.SculptType);
  253. List<Coord> coords;
  254. List<Face> faces;
  255. if (primShape.SculptEntry)
  256. {
  257. if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
  258. {
  259. if (!useMeshiesPhysicsMesh)
  260. return null;
  261. if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, size, out coords, out faces))
  262. return null;
  263. }
  264. else
  265. {
  266. if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, size, lod, out coords, out faces))
  267. return null;
  268. }
  269. }
  270. else
  271. {
  272. if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, size, lod, out coords, out faces))
  273. return null;
  274. }
  275. // Remove the reference to any JPEG2000 sculpt data so it can be GCed
  276. primShape.SculptData = Utils.EmptyBytes;
  277. int numCoords = coords.Count;
  278. int numFaces = faces.Count;
  279. // Create the list of vertices
  280. List<Vertex> vertices = new List<Vertex>();
  281. for (int i = 0; i < numCoords; i++)
  282. {
  283. Coord c = coords[i];
  284. vertices.Add(new Vertex(c.X, c.Y, c.Z));
  285. }
  286. Mesh mesh = new Mesh();
  287. // Add the corresponding triangles to the mesh
  288. for (int i = 0; i < numFaces; i++)
  289. {
  290. Face f = faces[i];
  291. mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
  292. }
  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, Vector3 size, out List<Coord> coords, out List<Face> faces)
  306. {
  307. // m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
  308. coords = new List<Coord>();
  309. faces = new List<Face>();
  310. OSD meshOsd = null;
  311. mConvexHulls = null;
  312. mBoundingHull = null;
  313. if (primShape.SculptData.Length <= 0)
  314. {
  315. // XXX: At the moment we can not log here since ODEPrim, for instance, ends up triggering this
  316. // method twice - once before it has loaded sculpt data from the asset service and once afterwards.
  317. // The first time will always call with unloaded SculptData if this needs to be uploaded.
  318. // m_log.ErrorFormat("[MESH]: asset data for {0} is zero length", primName);
  319. return false;
  320. }
  321. long start = 0;
  322. using (MemoryStream data = new MemoryStream(primShape.SculptData))
  323. {
  324. try
  325. {
  326. OSD osd = OSDParser.DeserializeLLSDBinary(data);
  327. if (osd is OSDMap)
  328. meshOsd = (OSDMap)osd;
  329. else
  330. {
  331. m_log.Warn("[Mesh}: unable to cast mesh asset to OSDMap");
  332. return false;
  333. }
  334. }
  335. catch (Exception e)
  336. {
  337. m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
  338. }
  339. start = data.Position;
  340. }
  341. if (meshOsd is OSDMap)
  342. {
  343. OSDMap physicsParms = null;
  344. OSDMap map = (OSDMap)meshOsd;
  345. if (map.ContainsKey("physics_shape"))
  346. {
  347. physicsParms = (OSDMap)map["physics_shape"]; // old asset format
  348. if (debugDetail) m_log.DebugFormat("{0} prim='{1}': using 'physics_shape' mesh data", LogHeader, primName);
  349. }
  350. else if (map.ContainsKey("physics_mesh"))
  351. {
  352. physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
  353. if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'physics_mesh' mesh data", LogHeader, primName);
  354. }
  355. else if (map.ContainsKey("medium_lod"))
  356. {
  357. physicsParms = (OSDMap)map["medium_lod"]; // if no physics mesh, try to fall back to medium LOD display mesh
  358. if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'medium_lod' mesh data", LogHeader, primName);
  359. }
  360. else if (map.ContainsKey("high_lod"))
  361. {
  362. physicsParms = (OSDMap)map["high_lod"]; // if all else fails, use highest LOD display mesh and hope it works :)
  363. if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'high_lod' mesh data", LogHeader, primName);
  364. }
  365. if (map.ContainsKey("physics_convex"))
  366. { // pull this out also in case physics engine can use it
  367. OSD convexBlockOsd = null;
  368. try
  369. {
  370. OSDMap convexBlock = (OSDMap)map["physics_convex"];
  371. {
  372. int convexOffset = convexBlock["offset"].AsInteger() + (int)start;
  373. int convexSize = convexBlock["size"].AsInteger();
  374. byte[] convexBytes = new byte[convexSize];
  375. System.Buffer.BlockCopy(primShape.SculptData, convexOffset, convexBytes, 0, convexSize);
  376. try
  377. {
  378. convexBlockOsd = DecompressOsd(convexBytes);
  379. }
  380. catch (Exception e)
  381. {
  382. m_log.ErrorFormat("{0} prim='{1}': exception decoding convex block: {2}", LogHeader, primName, e);
  383. //return false;
  384. }
  385. }
  386. if (convexBlockOsd != null && convexBlockOsd is OSDMap)
  387. {
  388. convexBlock = convexBlockOsd as OSDMap;
  389. if (debugDetail)
  390. {
  391. string keys = LogHeader + " keys found in convexBlock: ";
  392. foreach (KeyValuePair<string, OSD> kvp in convexBlock)
  393. keys += "'" + kvp.Key + "' ";
  394. m_log.Debug(keys);
  395. }
  396. Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f);
  397. if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3();
  398. Vector3 max = new Vector3(0.5f, 0.5f, 0.5f);
  399. if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3();
  400. List<Vector3> boundingHull = null;
  401. if (convexBlock.ContainsKey("BoundingVerts"))
  402. {
  403. byte[] boundingVertsBytes = convexBlock["BoundingVerts"].AsBinary();
  404. boundingHull = new List<Vector3>();
  405. for (int i = 0; i < boundingVertsBytes.Length; )
  406. {
  407. ushort uX = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2;
  408. ushort uY = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2;
  409. ushort uZ = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2;
  410. Vector3 pos = new Vector3(
  411. Utils.UInt16ToFloat(uX, min.X, max.X),
  412. Utils.UInt16ToFloat(uY, min.Y, max.Y),
  413. Utils.UInt16ToFloat(uZ, min.Z, max.Z)
  414. );
  415. boundingHull.Add(pos);
  416. }
  417. mBoundingHull = boundingHull;
  418. if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed bounding hull. nVerts={2}", LogHeader, primName, mBoundingHull.Count);
  419. }
  420. if (convexBlock.ContainsKey("HullList"))
  421. {
  422. byte[] hullList = convexBlock["HullList"].AsBinary();
  423. byte[] posBytes = convexBlock["Positions"].AsBinary();
  424. List<List<Vector3>> hulls = new List<List<Vector3>>();
  425. int posNdx = 0;
  426. foreach (byte cnt in hullList)
  427. {
  428. int count = cnt == 0 ? 256 : cnt;
  429. List<Vector3> hull = new List<Vector3>();
  430. for (int i = 0; i < count; i++)
  431. {
  432. ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2;
  433. ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2;
  434. ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2;
  435. Vector3 pos = new Vector3(
  436. Utils.UInt16ToFloat(uX, min.X, max.X),
  437. Utils.UInt16ToFloat(uY, min.Y, max.Y),
  438. Utils.UInt16ToFloat(uZ, min.Z, max.Z)
  439. );
  440. hull.Add(pos);
  441. }
  442. hulls.Add(hull);
  443. }
  444. mConvexHulls = hulls;
  445. if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed hulls. nHulls={2}", LogHeader, primName, mConvexHulls.Count);
  446. }
  447. else
  448. {
  449. if (debugDetail) m_log.DebugFormat("{0} prim='{1}' has physics_convex but no HullList", LogHeader, primName);
  450. }
  451. }
  452. }
  453. catch (Exception e)
  454. {
  455. m_log.WarnFormat("{0} exception decoding convex block: {1}", LogHeader, e);
  456. }
  457. }
  458. if (physicsParms == null)
  459. {
  460. m_log.WarnFormat("[MESH]: No recognized physics mesh found in mesh asset for {0}", primName);
  461. return false;
  462. }
  463. int physOffset = physicsParms["offset"].AsInteger() + (int)start;
  464. int physSize = physicsParms["size"].AsInteger();
  465. if (physOffset < 0 || physSize == 0)
  466. return false; // no mesh data in asset
  467. OSD decodedMeshOsd = new OSD();
  468. byte[] meshBytes = new byte[physSize];
  469. System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
  470. // byte[] decompressed = new byte[physSize * 5];
  471. try
  472. {
  473. decodedMeshOsd = DecompressOsd(meshBytes);
  474. }
  475. catch (Exception e)
  476. {
  477. m_log.ErrorFormat("{0} prim='{1}': exception decoding physical mesh: {2}", LogHeader, primName, e);
  478. return false;
  479. }
  480. OSDArray decodedMeshOsdArray = null;
  481. // physics_shape is an array of OSDMaps, one for each submesh
  482. if (decodedMeshOsd is OSDArray)
  483. {
  484. // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
  485. decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
  486. foreach (OSD subMeshOsd in decodedMeshOsdArray)
  487. {
  488. if (subMeshOsd is OSDMap)
  489. AddSubMesh(subMeshOsd as OSDMap, size, coords, faces);
  490. }
  491. if (debugDetail)
  492. m_log.DebugFormat("{0} {1}: mesh decoded. offset={2}, size={3}, nCoords={4}, nFaces={5}",
  493. LogHeader, primName, physOffset, physSize, coords.Count, faces.Count);
  494. }
  495. }
  496. return true;
  497. }
  498. /// <summary>
  499. /// decompresses a gzipped OSD object
  500. /// </summary>
  501. /// <param name="decodedOsd"></param> the OSD object
  502. /// <param name="meshBytes"></param>
  503. /// <returns></returns>
  504. private static OSD DecompressOsd(byte[] meshBytes)
  505. {
  506. OSD decodedOsd = null;
  507. using (MemoryStream outMs = new MemoryStream())
  508. {
  509. using (MemoryStream inMs = new MemoryStream(meshBytes))
  510. {
  511. using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
  512. {
  513. byte[] readBuffer = new byte[8192];
  514. inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
  515. int readLen = 0;
  516. while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  517. outMs.Write(readBuffer, 0, readLen);
  518. }
  519. }
  520. outMs.Seek(0, SeekOrigin.Begin);
  521. decodedOsd = OSDParser.DeserializeLLSDBinary(outMs);
  522. }
  523. return decodedOsd;
  524. }
  525. /// <summary>
  526. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  527. /// </summary>
  528. /// <param name="primName"></param>
  529. /// <param name="primShape"></param>
  530. /// <param name="size"></param>
  531. /// <param name="lod"></param>
  532. /// <param name="coords">Coords are added to this list by the method.</param>
  533. /// <param name="faces">Faces are added to this list by the method.</param>
  534. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  535. private bool GenerateCoordsAndFacesFromPrimSculptData(
  536. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  537. {
  538. coords = new List<Coord>();
  539. faces = new List<Face>();
  540. PrimMesher.SculptMesh sculptMesh;
  541. Image idata = null;
  542. string decodedSculptFileName = "";
  543. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  544. {
  545. decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
  546. try
  547. {
  548. if (File.Exists(decodedSculptFileName))
  549. {
  550. idata = Image.FromFile(decodedSculptFileName);
  551. }
  552. }
  553. catch (Exception e)
  554. {
  555. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  556. }
  557. //if (idata != null)
  558. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  559. }
  560. if (idata == null)
  561. {
  562. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  563. return false;
  564. try
  565. {
  566. OpenMetaverse.Imaging.ManagedImage managedImage;
  567. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage);
  568. if (managedImage == null)
  569. {
  570. // In some cases it seems that the decode can return a null bitmap without throwing
  571. // an exception
  572. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  573. return false;
  574. }
  575. if ((managedImage.Channels & OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha) != 0)
  576. managedImage.ConvertChannels(managedImage.Channels & ~OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha);
  577. Bitmap imgData = OpenMetaverse.Imaging.LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA()));
  578. idata = (Image)imgData;
  579. managedImage = null;
  580. if (cacheSculptMaps)
  581. {
  582. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  583. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  584. }
  585. }
  586. catch (DllNotFoundException)
  587. {
  588. 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!");
  589. return false;
  590. }
  591. catch (IndexOutOfRangeException)
  592. {
  593. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  594. return false;
  595. }
  596. catch (Exception ex)
  597. {
  598. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  599. return false;
  600. }
  601. }
  602. PrimMesher.SculptMesh.SculptType sculptType;
  603. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  604. {
  605. case OpenMetaverse.SculptType.Cylinder:
  606. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  607. break;
  608. case OpenMetaverse.SculptType.Plane:
  609. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  610. break;
  611. case OpenMetaverse.SculptType.Torus:
  612. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  613. break;
  614. case OpenMetaverse.SculptType.Sphere:
  615. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  616. break;
  617. default:
  618. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  619. break;
  620. }
  621. bool mirror = ((primShape.SculptType & 128) != 0);
  622. bool invert = ((primShape.SculptType & 64) != 0);
  623. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  624. idata.Dispose();
  625. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  626. sculptMesh.Scale(size.X, size.Y, size.Z);
  627. coords = sculptMesh.coords;
  628. faces = sculptMesh.faces;
  629. return true;
  630. }
  631. /// <summary>
  632. /// Generate the co-ords and faces necessary to construct a mesh from the shape 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="coords">Coords are added to this list by the method.</param>
  638. /// <param name="faces">Faces are added to this list by the method.</param>
  639. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  640. private bool GenerateCoordsAndFacesFromPrimShapeData(
  641. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  642. {
  643. PrimMesh primMesh;
  644. coords = new List<Coord>();
  645. faces = new List<Face>();
  646. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  647. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  648. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  649. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  650. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  651. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  652. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  653. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  654. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  655. if (profileHollow > 0.95f)
  656. profileHollow = 0.95f;
  657. int sides = 4;
  658. LevelOfDetail iLOD = (LevelOfDetail)lod;
  659. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  660. sides = 3;
  661. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  662. {
  663. switch (iLOD)
  664. {
  665. case LevelOfDetail.High: sides = 24; break;
  666. case LevelOfDetail.Medium: sides = 12; break;
  667. case LevelOfDetail.Low: sides = 6; break;
  668. case LevelOfDetail.VeryLow: sides = 3; break;
  669. default: sides = 24; break;
  670. }
  671. }
  672. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  673. { // half circle, prim is a sphere
  674. switch (iLOD)
  675. {
  676. case LevelOfDetail.High: sides = 24; break;
  677. case LevelOfDetail.Medium: sides = 12; break;
  678. case LevelOfDetail.Low: sides = 6; break;
  679. case LevelOfDetail.VeryLow: sides = 3; break;
  680. default: sides = 24; break;
  681. }
  682. profileBegin = 0.5f * profileBegin + 0.5f;
  683. profileEnd = 0.5f * profileEnd + 0.5f;
  684. }
  685. int hollowSides = sides;
  686. if (primShape.HollowShape == HollowShape.Circle)
  687. {
  688. switch (iLOD)
  689. {
  690. case LevelOfDetail.High: hollowSides = 24; break;
  691. case LevelOfDetail.Medium: hollowSides = 12; break;
  692. case LevelOfDetail.Low: hollowSides = 6; break;
  693. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  694. default: hollowSides = 24; break;
  695. }
  696. }
  697. else if (primShape.HollowShape == HollowShape.Square)
  698. hollowSides = 4;
  699. else if (primShape.HollowShape == HollowShape.Triangle)
  700. hollowSides = 3;
  701. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  702. if (primMesh.errorMessage != null)
  703. if (primMesh.errorMessage.Length > 0)
  704. m_log.Error("[ERROR] " + primMesh.errorMessage);
  705. primMesh.topShearX = pathShearX;
  706. primMesh.topShearY = pathShearY;
  707. primMesh.pathCutBegin = pathBegin;
  708. primMesh.pathCutEnd = pathEnd;
  709. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  710. {
  711. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  712. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  713. primMesh.taperX = pathScaleX;
  714. primMesh.taperY = pathScaleY;
  715. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  716. {
  717. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  718. if (profileBegin < 0.0f) profileBegin = 0.0f;
  719. if (profileEnd > 1.0f) profileEnd = 1.0f;
  720. }
  721. #if SPAM
  722. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  723. #endif
  724. try
  725. {
  726. primMesh.ExtrudeLinear();
  727. }
  728. catch (Exception ex)
  729. {
  730. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  731. return false;
  732. }
  733. }
  734. else
  735. {
  736. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  737. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  738. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  739. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  740. primMesh.skew = 0.01f * primShape.PathSkew;
  741. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  742. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  743. primMesh.taperX = primShape.PathTaperX * 0.01f;
  744. primMesh.taperY = primShape.PathTaperY * 0.01f;
  745. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  746. {
  747. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  748. if (profileBegin < 0.0f) profileBegin = 0.0f;
  749. if (profileEnd > 1.0f) profileEnd = 1.0f;
  750. }
  751. #if SPAM
  752. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  753. #endif
  754. try
  755. {
  756. primMesh.ExtrudeCircular();
  757. }
  758. catch (Exception ex)
  759. {
  760. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  761. return false;
  762. }
  763. }
  764. primMesh.DumpRaw(baseDir, primName, "primMesh");
  765. primMesh.Scale(size.X, size.Y, size.Z);
  766. coords = primMesh.coords;
  767. faces = primMesh.faces;
  768. return true;
  769. }
  770. /// <summary>
  771. /// temporary prototype code - please do not use until the interface has been finalized!
  772. /// </summary>
  773. /// <param name="size">value to scale the hull points by</param>
  774. /// <returns>a list of vertices in the bounding hull if it exists and has been successfully decoded, otherwise null</returns>
  775. public List<Vector3> GetBoundingHull(Vector3 size)
  776. {
  777. if (mBoundingHull == null)
  778. return null;
  779. List<Vector3> verts = new List<Vector3>();
  780. foreach (var vert in mBoundingHull)
  781. verts.Add(vert * size);
  782. return verts;
  783. }
  784. /// <summary>
  785. /// temporary prototype code - please do not use until the interface has been finalized!
  786. /// </summary>
  787. /// <param name="size">value to scale the hull points by</param>
  788. /// <returns>a list of hulls if they exist and have been successfully decoded, otherwise null</returns>
  789. public List<List<Vector3>> GetConvexHulls(Vector3 size)
  790. {
  791. if (mConvexHulls == null)
  792. return null;
  793. List<List<Vector3>> hulls = new List<List<Vector3>>();
  794. foreach (var hull in mConvexHulls)
  795. {
  796. List<Vector3> verts = new List<Vector3>();
  797. foreach (var vert in hull)
  798. verts.Add(vert * size);
  799. hulls.Add(verts);
  800. }
  801. return hulls;
  802. }
  803. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  804. {
  805. return CreateMesh(primName, primShape, size, lod, false, true);
  806. }
  807. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, bool convex, bool forOde)
  808. {
  809. return CreateMesh(primName, primShape, size, lod, false);
  810. }
  811. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  812. {
  813. return CreateMesh(primName, primShape, size, lod, isPhysical, true);
  814. }
  815. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex, bool forOde)
  816. {
  817. return CreateMesh(primName, primShape, size, lod, isPhysical, true);
  818. }
  819. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache)
  820. {
  821. #if SPAM
  822. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  823. #endif
  824. Mesh mesh = null;
  825. ulong key = 0;
  826. // If this mesh has been created already, return it instead of creating another copy
  827. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  828. if (shouldCache)
  829. {
  830. key = primShape.GetMeshKey(size, lod);
  831. lock (m_uniqueMeshes)
  832. {
  833. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  834. return mesh;
  835. }
  836. }
  837. if (size.X < 0.01f) size.X = 0.01f;
  838. if (size.Y < 0.01f) size.Y = 0.01f;
  839. if (size.Z < 0.01f) size.Z = 0.01f;
  840. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  841. if (mesh != null)
  842. {
  843. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  844. {
  845. #if SPAM
  846. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  847. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  848. #endif
  849. mesh = CreateBoundingBoxMesh(mesh);
  850. mesh.DumpRaw(baseDir, primName, "Z extruded");
  851. }
  852. // trim the vertex and triangle lists to free up memory
  853. mesh.TrimExcess();
  854. if (shouldCache)
  855. {
  856. lock (m_uniqueMeshes)
  857. {
  858. m_uniqueMeshes.Add(key, mesh);
  859. }
  860. }
  861. }
  862. return mesh;
  863. }
  864. public IMesh GetMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex)
  865. {
  866. return null;
  867. }
  868. public void ReleaseMesh(IMesh imesh) { }
  869. public void ExpireReleaseMeshs() { }
  870. public void ExpireFileCache() { }
  871. }
  872. }