Meshmerizer.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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 inMs = new MemoryStream(meshBytes))
  508. {
  509. using (MemoryStream outMs = new MemoryStream())
  510. {
  511. using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
  512. {
  513. byte[] readBuffer = new byte[2048];
  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. outMs.Flush();
  519. outMs.Seek(0, SeekOrigin.Begin);
  520. byte[] decompressedBuf = outMs.GetBuffer();
  521. decodedOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
  522. }
  523. }
  524. }
  525. return decodedOsd;
  526. }
  527. /// <summary>
  528. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  529. /// </summary>
  530. /// <param name="primName"></param>
  531. /// <param name="primShape"></param>
  532. /// <param name="size"></param>
  533. /// <param name="lod"></param>
  534. /// <param name="coords">Coords are added to this list by the method.</param>
  535. /// <param name="faces">Faces are added to this list by the method.</param>
  536. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  537. private bool GenerateCoordsAndFacesFromPrimSculptData(
  538. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  539. {
  540. coords = new List<Coord>();
  541. faces = new List<Face>();
  542. PrimMesher.SculptMesh sculptMesh;
  543. Image idata = null;
  544. string decodedSculptFileName = "";
  545. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  546. {
  547. decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
  548. try
  549. {
  550. if (File.Exists(decodedSculptFileName))
  551. {
  552. idata = Image.FromFile(decodedSculptFileName);
  553. }
  554. }
  555. catch (Exception e)
  556. {
  557. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  558. }
  559. //if (idata != null)
  560. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  561. }
  562. if (idata == null)
  563. {
  564. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  565. return false;
  566. try
  567. {
  568. OpenMetaverse.Imaging.ManagedImage managedImage;
  569. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage);
  570. if (managedImage == null)
  571. {
  572. // In some cases it seems that the decode can return a null bitmap without throwing
  573. // an exception
  574. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  575. return false;
  576. }
  577. if ((managedImage.Channels & OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha) != 0)
  578. managedImage.ConvertChannels(managedImage.Channels & ~OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha);
  579. Bitmap imgData = OpenMetaverse.Imaging.LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA()));
  580. idata = (Image)imgData;
  581. managedImage = null;
  582. if (cacheSculptMaps)
  583. {
  584. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  585. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  586. }
  587. }
  588. catch (DllNotFoundException)
  589. {
  590. 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!");
  591. return false;
  592. }
  593. catch (IndexOutOfRangeException)
  594. {
  595. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  596. return false;
  597. }
  598. catch (Exception ex)
  599. {
  600. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  601. return false;
  602. }
  603. }
  604. PrimMesher.SculptMesh.SculptType sculptType;
  605. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  606. {
  607. case OpenMetaverse.SculptType.Cylinder:
  608. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  609. break;
  610. case OpenMetaverse.SculptType.Plane:
  611. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  612. break;
  613. case OpenMetaverse.SculptType.Torus:
  614. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  615. break;
  616. case OpenMetaverse.SculptType.Sphere:
  617. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  618. break;
  619. default:
  620. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  621. break;
  622. }
  623. bool mirror = ((primShape.SculptType & 128) != 0);
  624. bool invert = ((primShape.SculptType & 64) != 0);
  625. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  626. idata.Dispose();
  627. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  628. sculptMesh.Scale(size.X, size.Y, size.Z);
  629. coords = sculptMesh.coords;
  630. faces = sculptMesh.faces;
  631. return true;
  632. }
  633. /// <summary>
  634. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  635. /// </summary>
  636. /// <param name="primName"></param>
  637. /// <param name="primShape"></param>
  638. /// <param name="size"></param>
  639. /// <param name="coords">Coords are added to this list by the method.</param>
  640. /// <param name="faces">Faces are added to this list by the method.</param>
  641. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  642. private bool GenerateCoordsAndFacesFromPrimShapeData(
  643. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  644. {
  645. PrimMesh primMesh;
  646. coords = new List<Coord>();
  647. faces = new List<Face>();
  648. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  649. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  650. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  651. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  652. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  653. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  654. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  655. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  656. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  657. if (profileHollow > 0.95f)
  658. profileHollow = 0.95f;
  659. int sides = 4;
  660. LevelOfDetail iLOD = (LevelOfDetail)lod;
  661. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  662. sides = 3;
  663. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  664. {
  665. switch (iLOD)
  666. {
  667. case LevelOfDetail.High: sides = 24; break;
  668. case LevelOfDetail.Medium: sides = 12; break;
  669. case LevelOfDetail.Low: sides = 6; break;
  670. case LevelOfDetail.VeryLow: sides = 3; break;
  671. default: sides = 24; break;
  672. }
  673. }
  674. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  675. { // half circle, prim is a sphere
  676. switch (iLOD)
  677. {
  678. case LevelOfDetail.High: sides = 24; break;
  679. case LevelOfDetail.Medium: sides = 12; break;
  680. case LevelOfDetail.Low: sides = 6; break;
  681. case LevelOfDetail.VeryLow: sides = 3; break;
  682. default: sides = 24; break;
  683. }
  684. profileBegin = 0.5f * profileBegin + 0.5f;
  685. profileEnd = 0.5f * profileEnd + 0.5f;
  686. }
  687. int hollowSides = sides;
  688. if (primShape.HollowShape == HollowShape.Circle)
  689. {
  690. switch (iLOD)
  691. {
  692. case LevelOfDetail.High: hollowSides = 24; break;
  693. case LevelOfDetail.Medium: hollowSides = 12; break;
  694. case LevelOfDetail.Low: hollowSides = 6; break;
  695. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  696. default: hollowSides = 24; break;
  697. }
  698. }
  699. else if (primShape.HollowShape == HollowShape.Square)
  700. hollowSides = 4;
  701. else if (primShape.HollowShape == HollowShape.Triangle)
  702. hollowSides = 3;
  703. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  704. if (primMesh.errorMessage != null)
  705. if (primMesh.errorMessage.Length > 0)
  706. m_log.Error("[ERROR] " + primMesh.errorMessage);
  707. primMesh.topShearX = pathShearX;
  708. primMesh.topShearY = pathShearY;
  709. primMesh.pathCutBegin = pathBegin;
  710. primMesh.pathCutEnd = pathEnd;
  711. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  712. {
  713. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  714. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  715. primMesh.taperX = pathScaleX;
  716. primMesh.taperY = pathScaleY;
  717. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  718. {
  719. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  720. if (profileBegin < 0.0f) profileBegin = 0.0f;
  721. if (profileEnd > 1.0f) profileEnd = 1.0f;
  722. }
  723. #if SPAM
  724. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  725. #endif
  726. try
  727. {
  728. primMesh.ExtrudeLinear();
  729. }
  730. catch (Exception ex)
  731. {
  732. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  733. return false;
  734. }
  735. }
  736. else
  737. {
  738. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  739. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  740. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  741. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  742. primMesh.skew = 0.01f * primShape.PathSkew;
  743. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  744. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  745. primMesh.taperX = primShape.PathTaperX * 0.01f;
  746. primMesh.taperY = primShape.PathTaperY * 0.01f;
  747. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  748. {
  749. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  750. if (profileBegin < 0.0f) profileBegin = 0.0f;
  751. if (profileEnd > 1.0f) profileEnd = 1.0f;
  752. }
  753. #if SPAM
  754. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  755. #endif
  756. try
  757. {
  758. primMesh.ExtrudeCircular();
  759. }
  760. catch (Exception ex)
  761. {
  762. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  763. return false;
  764. }
  765. }
  766. primMesh.DumpRaw(baseDir, primName, "primMesh");
  767. primMesh.Scale(size.X, size.Y, size.Z);
  768. coords = primMesh.coords;
  769. faces = primMesh.faces;
  770. return true;
  771. }
  772. /// <summary>
  773. /// temporary prototype code - please do not use until the interface has been finalized!
  774. /// </summary>
  775. /// <param name="size">value to scale the hull points by</param>
  776. /// <returns>a list of vertices in the bounding hull if it exists and has been successfully decoded, otherwise null</returns>
  777. public List<Vector3> GetBoundingHull(Vector3 size)
  778. {
  779. if (mBoundingHull == null)
  780. return null;
  781. List<Vector3> verts = new List<Vector3>();
  782. foreach (var vert in mBoundingHull)
  783. verts.Add(vert * size);
  784. return verts;
  785. }
  786. /// <summary>
  787. /// temporary prototype code - please do not use until the interface has been finalized!
  788. /// </summary>
  789. /// <param name="size">value to scale the hull points by</param>
  790. /// <returns>a list of hulls if they exist and have been successfully decoded, otherwise null</returns>
  791. public List<List<Vector3>> GetConvexHulls(Vector3 size)
  792. {
  793. if (mConvexHulls == null)
  794. return null;
  795. List<List<Vector3>> hulls = new List<List<Vector3>>();
  796. foreach (var hull in mConvexHulls)
  797. {
  798. List<Vector3> verts = new List<Vector3>();
  799. foreach (var vert in hull)
  800. verts.Add(vert * size);
  801. hulls.Add(verts);
  802. }
  803. return hulls;
  804. }
  805. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  806. {
  807. return CreateMesh(primName, primShape, size, lod, false, true);
  808. }
  809. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, bool convex, bool forOde)
  810. {
  811. return CreateMesh(primName, primShape, size, lod, false);
  812. }
  813. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  814. {
  815. return CreateMesh(primName, primShape, size, lod, isPhysical, true);
  816. }
  817. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex, bool forOde)
  818. {
  819. return CreateMesh(primName, primShape, size, lod, isPhysical, true);
  820. }
  821. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache)
  822. {
  823. #if SPAM
  824. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  825. #endif
  826. Mesh mesh = null;
  827. ulong key = 0;
  828. // If this mesh has been created already, return it instead of creating another copy
  829. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  830. if (shouldCache)
  831. {
  832. key = primShape.GetMeshKey(size, lod);
  833. lock (m_uniqueMeshes)
  834. {
  835. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  836. return mesh;
  837. }
  838. }
  839. if (size.X < 0.01f) size.X = 0.01f;
  840. if (size.Y < 0.01f) size.Y = 0.01f;
  841. if (size.Z < 0.01f) size.Z = 0.01f;
  842. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  843. if (mesh != null)
  844. {
  845. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  846. {
  847. #if SPAM
  848. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  849. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  850. #endif
  851. mesh = CreateBoundingBoxMesh(mesh);
  852. mesh.DumpRaw(baseDir, primName, "Z extruded");
  853. }
  854. // trim the vertex and triangle lists to free up memory
  855. mesh.TrimExcess();
  856. if (shouldCache)
  857. {
  858. lock (m_uniqueMeshes)
  859. {
  860. m_uniqueMeshes.Add(key, mesh);
  861. }
  862. }
  863. }
  864. return mesh;
  865. }
  866. public IMesh GetMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex)
  867. {
  868. return null;
  869. }
  870. public void ReleaseMesh(IMesh imesh) { }
  871. public void ExpireReleaseMeshs() { }
  872. public void ExpireFileCache() { }
  873. }
  874. }