Meshmerizer.cs 41 KB

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