Meshmerizer.cs 42 KB

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