1
0

Meshmerizer.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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. using ComponentAce.Compression.Libs.zlib;
  43. namespace OpenSim.Region.Physics.Meshing
  44. {
  45. public class MeshmerizerPlugin : IMeshingPlugin
  46. {
  47. public MeshmerizerPlugin()
  48. {
  49. }
  50. public string GetName()
  51. {
  52. return "Meshmerizer";
  53. }
  54. public IMesher GetMesher(IConfigSource config)
  55. {
  56. return new Meshmerizer(config);
  57. }
  58. }
  59. public class Meshmerizer : IMesher
  60. {
  61. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  62. private static string LogHeader = "[MESH]";
  63. // Setting baseDir to a path will enable the dumping of raw files
  64. // raw files can be imported by blender so a visual inspection of the results can be done
  65. #if SPAM
  66. const string baseDir = "rawFiles";
  67. #else
  68. private const string baseDir = null; //"rawFiles";
  69. #endif
  70. // If 'true', lots of DEBUG logging of asset parsing details
  71. private bool debugDetail = false;
  72. private bool cacheSculptMaps = true;
  73. private string decodedSculptMapPath = null;
  74. private bool useMeshiesPhysicsMesh = false;
  75. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  76. private List<List<Vector3>> mConvexHulls = null;
  77. private List<Vector3> mBoundingHull = null;
  78. private 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 (ZOutputStream zOut = new ZOutputStream(outMs))
  483. {
  484. byte[] readBuffer = new byte[2048];
  485. int readLen = 0;
  486. while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
  487. {
  488. zOut.Write(readBuffer, 0, readLen);
  489. }
  490. zOut.Flush();
  491. outMs.Seek(0, SeekOrigin.Begin);
  492. byte[] decompressedBuf = outMs.GetBuffer();
  493. decodedOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
  494. }
  495. }
  496. }
  497. return decodedOsd;
  498. }
  499. /// <summary>
  500. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  501. /// </summary>
  502. /// <param name="primName"></param>
  503. /// <param name="primShape"></param>
  504. /// <param name="size"></param>
  505. /// <param name="lod"></param>
  506. /// <param name="coords">Coords are added to this list by the method.</param>
  507. /// <param name="faces">Faces are added to this list by the method.</param>
  508. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  509. private bool GenerateCoordsAndFacesFromPrimSculptData(
  510. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  511. {
  512. coords = new List<Coord>();
  513. faces = new List<Face>();
  514. PrimMesher.SculptMesh sculptMesh;
  515. Image idata = null;
  516. string decodedSculptFileName = "";
  517. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  518. {
  519. decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
  520. try
  521. {
  522. if (File.Exists(decodedSculptFileName))
  523. {
  524. idata = Image.FromFile(decodedSculptFileName);
  525. }
  526. }
  527. catch (Exception e)
  528. {
  529. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  530. }
  531. //if (idata != null)
  532. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  533. }
  534. if (idata == null)
  535. {
  536. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  537. return false;
  538. try
  539. {
  540. OpenMetaverse.Imaging.ManagedImage unusedData;
  541. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
  542. if (idata == null)
  543. {
  544. // In some cases it seems that the decode can return a null bitmap without throwing
  545. // an exception
  546. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  547. return false;
  548. }
  549. unusedData = null;
  550. //idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData);
  551. if (cacheSculptMaps)
  552. {
  553. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  554. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  555. }
  556. }
  557. catch (DllNotFoundException)
  558. {
  559. 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!");
  560. return false;
  561. }
  562. catch (IndexOutOfRangeException)
  563. {
  564. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  565. return false;
  566. }
  567. catch (Exception ex)
  568. {
  569. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  570. return false;
  571. }
  572. }
  573. PrimMesher.SculptMesh.SculptType sculptType;
  574. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  575. {
  576. case OpenMetaverse.SculptType.Cylinder:
  577. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  578. break;
  579. case OpenMetaverse.SculptType.Plane:
  580. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  581. break;
  582. case OpenMetaverse.SculptType.Torus:
  583. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  584. break;
  585. case OpenMetaverse.SculptType.Sphere:
  586. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  587. break;
  588. default:
  589. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  590. break;
  591. }
  592. bool mirror = ((primShape.SculptType & 128) != 0);
  593. bool invert = ((primShape.SculptType & 64) != 0);
  594. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  595. idata.Dispose();
  596. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  597. sculptMesh.Scale(size.X, size.Y, size.Z);
  598. coords = sculptMesh.coords;
  599. faces = sculptMesh.faces;
  600. return true;
  601. }
  602. /// <summary>
  603. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  604. /// </summary>
  605. /// <param name="primName"></param>
  606. /// <param name="primShape"></param>
  607. /// <param name="size"></param>
  608. /// <param name="coords">Coords are added to this list by the method.</param>
  609. /// <param name="faces">Faces are added to this list by the method.</param>
  610. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  611. private bool GenerateCoordsAndFacesFromPrimShapeData(
  612. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  613. {
  614. PrimMesh primMesh;
  615. coords = new List<Coord>();
  616. faces = new List<Face>();
  617. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  618. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  619. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  620. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  621. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  622. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  623. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  624. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  625. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  626. if (profileHollow > 0.95f)
  627. profileHollow = 0.95f;
  628. int sides = 4;
  629. LevelOfDetail iLOD = (LevelOfDetail)lod;
  630. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  631. sides = 3;
  632. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  633. {
  634. switch (iLOD)
  635. {
  636. case LevelOfDetail.High: sides = 24; break;
  637. case LevelOfDetail.Medium: sides = 12; break;
  638. case LevelOfDetail.Low: sides = 6; break;
  639. case LevelOfDetail.VeryLow: sides = 3; break;
  640. default: sides = 24; break;
  641. }
  642. }
  643. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  644. { // half circle, prim is a sphere
  645. switch (iLOD)
  646. {
  647. case LevelOfDetail.High: sides = 24; break;
  648. case LevelOfDetail.Medium: sides = 12; break;
  649. case LevelOfDetail.Low: sides = 6; break;
  650. case LevelOfDetail.VeryLow: sides = 3; break;
  651. default: sides = 24; break;
  652. }
  653. profileBegin = 0.5f * profileBegin + 0.5f;
  654. profileEnd = 0.5f * profileEnd + 0.5f;
  655. }
  656. int hollowSides = sides;
  657. if (primShape.HollowShape == HollowShape.Circle)
  658. {
  659. switch (iLOD)
  660. {
  661. case LevelOfDetail.High: hollowSides = 24; break;
  662. case LevelOfDetail.Medium: hollowSides = 12; break;
  663. case LevelOfDetail.Low: hollowSides = 6; break;
  664. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  665. default: hollowSides = 24; break;
  666. }
  667. }
  668. else if (primShape.HollowShape == HollowShape.Square)
  669. hollowSides = 4;
  670. else if (primShape.HollowShape == HollowShape.Triangle)
  671. hollowSides = 3;
  672. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  673. if (primMesh.errorMessage != null)
  674. if (primMesh.errorMessage.Length > 0)
  675. m_log.Error("[ERROR] " + primMesh.errorMessage);
  676. primMesh.topShearX = pathShearX;
  677. primMesh.topShearY = pathShearY;
  678. primMesh.pathCutBegin = pathBegin;
  679. primMesh.pathCutEnd = pathEnd;
  680. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  681. {
  682. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  683. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  684. primMesh.taperX = pathScaleX;
  685. primMesh.taperY = pathScaleY;
  686. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  687. {
  688. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  689. if (profileBegin < 0.0f) profileBegin = 0.0f;
  690. if (profileEnd > 1.0f) profileEnd = 1.0f;
  691. }
  692. #if SPAM
  693. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  694. #endif
  695. try
  696. {
  697. primMesh.ExtrudeLinear();
  698. }
  699. catch (Exception ex)
  700. {
  701. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  702. return false;
  703. }
  704. }
  705. else
  706. {
  707. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  708. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  709. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  710. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  711. primMesh.skew = 0.01f * primShape.PathSkew;
  712. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  713. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  714. primMesh.taperX = primShape.PathTaperX * 0.01f;
  715. primMesh.taperY = primShape.PathTaperY * 0.01f;
  716. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  717. {
  718. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  719. if (profileBegin < 0.0f) profileBegin = 0.0f;
  720. if (profileEnd > 1.0f) profileEnd = 1.0f;
  721. }
  722. #if SPAM
  723. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  724. #endif
  725. try
  726. {
  727. primMesh.ExtrudeCircular();
  728. }
  729. catch (Exception ex)
  730. {
  731. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  732. return false;
  733. }
  734. }
  735. primMesh.DumpRaw(baseDir, primName, "primMesh");
  736. primMesh.Scale(size.X, size.Y, size.Z);
  737. coords = primMesh.coords;
  738. faces = primMesh.faces;
  739. return true;
  740. }
  741. /// <summary>
  742. /// temporary prototype code - please do not use until the interface has been finalized!
  743. /// </summary>
  744. /// <param name="size">value to scale the hull points by</param>
  745. /// <returns>a list of vertices in the bounding hull if it exists and has been successfully decoded, otherwise null</returns>
  746. public List<Vector3> GetBoundingHull(Vector3 size)
  747. {
  748. if (mBoundingHull == null)
  749. return null;
  750. List<Vector3> verts = new List<Vector3>();
  751. foreach (var vert in mBoundingHull)
  752. verts.Add(vert * size);
  753. return verts;
  754. }
  755. /// <summary>
  756. /// temporary prototype code - please do not use until the interface has been finalized!
  757. /// </summary>
  758. /// <param name="size">value to scale the hull points by</param>
  759. /// <returns>a list of hulls if they exist and have been successfully decoded, otherwise null</returns>
  760. public List<List<Vector3>> GetConvexHulls(Vector3 size)
  761. {
  762. if (mConvexHulls == null)
  763. return null;
  764. List<List<Vector3>> hulls = new List<List<Vector3>>();
  765. foreach (var hull in mConvexHulls)
  766. {
  767. List<Vector3> verts = new List<Vector3>();
  768. foreach (var vert in hull)
  769. verts.Add(vert * size);
  770. hulls.Add(verts);
  771. }
  772. return hulls;
  773. }
  774. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  775. {
  776. return CreateMesh(primName, primShape, size, lod, false, true);
  777. }
  778. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  779. {
  780. return CreateMesh(primName, primShape, size, lod, isPhysical, true);
  781. }
  782. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache)
  783. {
  784. #if SPAM
  785. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  786. #endif
  787. Mesh mesh = null;
  788. ulong key = 0;
  789. // If this mesh has been created already, return it instead of creating another copy
  790. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  791. if (shouldCache)
  792. {
  793. key = primShape.GetMeshKey(size, lod);
  794. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  795. return mesh;
  796. }
  797. if (size.X < 0.01f) size.X = 0.01f;
  798. if (size.Y < 0.01f) size.Y = 0.01f;
  799. if (size.Z < 0.01f) size.Z = 0.01f;
  800. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  801. if (mesh != null)
  802. {
  803. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  804. {
  805. #if SPAM
  806. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  807. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  808. #endif
  809. mesh = CreateBoundingBoxMesh(mesh);
  810. mesh.DumpRaw(baseDir, primName, "Z extruded");
  811. }
  812. // trim the vertex and triangle lists to free up memory
  813. mesh.TrimExcess();
  814. if (shouldCache)
  815. {
  816. m_uniqueMeshes.Add(key, mesh);
  817. }
  818. }
  819. return mesh;
  820. }
  821. }
  822. }