Meshmerizer.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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. // 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. private bool cacheSculptMaps = true;
  70. private string decodedSculptMapPath = null;
  71. private bool useMeshiesPhysicsMesh = false;
  72. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  73. private Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
  74. public Meshmerizer(IConfigSource config)
  75. {
  76. IConfig start_config = config.Configs["Startup"];
  77. IConfig mesh_config = config.Configs["Mesh"];
  78. decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath","j2kDecodeCache");
  79. cacheSculptMaps = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
  80. if(mesh_config != null)
  81. useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
  82. try
  83. {
  84. if (!Directory.Exists(decodedSculptMapPath))
  85. Directory.CreateDirectory(decodedSculptMapPath);
  86. }
  87. catch (Exception e)
  88. {
  89. m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath, e.Message);
  90. }
  91. }
  92. /// <summary>
  93. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  94. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  95. /// for some reason
  96. /// </summary>
  97. /// <param name="minX"></param>
  98. /// <param name="maxX"></param>
  99. /// <param name="minY"></param>
  100. /// <param name="maxY"></param>
  101. /// <param name="minZ"></param>
  102. /// <param name="maxZ"></param>
  103. /// <returns></returns>
  104. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  105. {
  106. Mesh box = new Mesh();
  107. List<Vertex> vertices = new List<Vertex>();
  108. // bottom
  109. vertices.Add(new Vertex(minX, maxY, minZ));
  110. vertices.Add(new Vertex(maxX, maxY, minZ));
  111. vertices.Add(new Vertex(maxX, minY, minZ));
  112. vertices.Add(new Vertex(minX, minY, minZ));
  113. box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
  114. box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
  115. // top
  116. vertices.Add(new Vertex(maxX, maxY, maxZ));
  117. vertices.Add(new Vertex(minX, maxY, maxZ));
  118. vertices.Add(new Vertex(minX, minY, maxZ));
  119. vertices.Add(new Vertex(maxX, minY, maxZ));
  120. box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
  121. box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
  122. // sides
  123. box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
  124. box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
  125. box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
  126. box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
  127. box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
  128. box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
  129. box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
  130. box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
  131. return box;
  132. }
  133. /// <summary>
  134. /// Creates a simple bounding box mesh for a complex input mesh
  135. /// </summary>
  136. /// <param name="meshIn"></param>
  137. /// <returns></returns>
  138. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  139. {
  140. float minX = float.MaxValue;
  141. float maxX = float.MinValue;
  142. float minY = float.MaxValue;
  143. float maxY = float.MinValue;
  144. float minZ = float.MaxValue;
  145. float maxZ = float.MinValue;
  146. foreach (Vector3 v in meshIn.getVertexList())
  147. {
  148. if (v.X < minX) minX = v.X;
  149. if (v.Y < minY) minY = v.Y;
  150. if (v.Z < minZ) minZ = v.Z;
  151. if (v.X > maxX) maxX = v.X;
  152. if (v.Y > maxY) maxY = v.Y;
  153. if (v.Z > maxZ) maxZ = v.Z;
  154. }
  155. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  156. }
  157. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  158. {
  159. m_log.Error(message);
  160. m_log.Error("\nPrim Name: " + primName);
  161. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  162. }
  163. /// <summary>
  164. /// Add a submesh to an existing list of coords and faces.
  165. /// </summary>
  166. /// <param name="subMeshData"></param>
  167. /// <param name="size">Size of entire object</param>
  168. /// <param name="coords"></param>
  169. /// <param name="faces"></param>
  170. private void AddSubMesh(OSDMap subMeshData, Vector3 size, List<Coord> coords, List<Face> faces)
  171. {
  172. // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
  173. // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
  174. // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
  175. // geometry for this submesh.
  176. if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
  177. return;
  178. OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
  179. OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
  180. ushort faceIndexOffset = (ushort)coords.Count;
  181. byte[] posBytes = subMeshData["Position"].AsBinary();
  182. for (int i = 0; i < posBytes.Length; i += 6)
  183. {
  184. ushort uX = Utils.BytesToUInt16(posBytes, i);
  185. ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
  186. ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
  187. Coord c = new Coord(
  188. Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X,
  189. Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y,
  190. Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z);
  191. coords.Add(c);
  192. }
  193. byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
  194. for (int i = 0; i < triangleBytes.Length; i += 6)
  195. {
  196. ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
  197. ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
  198. ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
  199. Face f = new Face(v1, v2, v3);
  200. faces.Add(f);
  201. }
  202. }
  203. /// <summary>
  204. /// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
  205. /// </summary>
  206. /// <param name="primName"></param>
  207. /// <param name="primShape"></param>
  208. /// <param name="size"></param>
  209. /// <param name="lod"></param>
  210. /// <returns></returns>
  211. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  212. {
  213. // m_log.DebugFormat(
  214. // "[MESH]: Creating physics proxy for {0}, shape {1}",
  215. // primName, (OpenMetaverse.SculptType)primShape.SculptType);
  216. List<Coord> coords;
  217. List<Face> faces;
  218. if (primShape.SculptEntry)
  219. {
  220. if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
  221. {
  222. if (!useMeshiesPhysicsMesh)
  223. return null;
  224. if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, size, out coords, out faces))
  225. return null;
  226. }
  227. else
  228. {
  229. if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, size, lod, out coords, out faces))
  230. return null;
  231. }
  232. }
  233. else
  234. {
  235. if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, size, lod, out coords, out faces))
  236. return null;
  237. }
  238. // Remove the reference to any JPEG2000 sculpt data so it can be GCed
  239. primShape.SculptData = Utils.EmptyBytes;
  240. int numCoords = coords.Count;
  241. int numFaces = faces.Count;
  242. // Create the list of vertices
  243. List<Vertex> vertices = new List<Vertex>();
  244. for (int i = 0; i < numCoords; i++)
  245. {
  246. Coord c = coords[i];
  247. vertices.Add(new Vertex(c.X, c.Y, c.Z));
  248. }
  249. Mesh mesh = new Mesh();
  250. // Add the corresponding triangles to the mesh
  251. for (int i = 0; i < numFaces; i++)
  252. {
  253. Face f = faces[i];
  254. mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
  255. }
  256. return mesh;
  257. }
  258. /// <summary>
  259. /// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
  260. /// </summary>
  261. /// <param name="primName"></param>
  262. /// <param name="primShape"></param>
  263. /// <param name="size"></param>
  264. /// <param name="coords">Coords are added to this list by the method.</param>
  265. /// <param name="faces">Faces are added to this list by the method.</param>
  266. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  267. private bool GenerateCoordsAndFacesFromPrimMeshData(
  268. string primName, PrimitiveBaseShape primShape, Vector3 size, out List<Coord> coords, out List<Face> faces)
  269. {
  270. // m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
  271. coords = new List<Coord>();
  272. faces = new List<Face>();
  273. OSD meshOsd = null;
  274. if (primShape.SculptData.Length <= 0)
  275. {
  276. m_log.ErrorFormat("[MESH]: asset data for {0} is zero length", primName);
  277. return false;
  278. }
  279. long start = 0;
  280. using (MemoryStream data = new MemoryStream(primShape.SculptData))
  281. {
  282. try
  283. {
  284. OSD osd = OSDParser.DeserializeLLSDBinary(data);
  285. if (osd is OSDMap)
  286. meshOsd = (OSDMap)osd;
  287. else
  288. {
  289. m_log.Warn("[Mesh}: unable to cast mesh asset to OSDMap");
  290. return false;
  291. }
  292. }
  293. catch (Exception e)
  294. {
  295. m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
  296. }
  297. start = data.Position;
  298. }
  299. if (meshOsd is OSDMap)
  300. {
  301. OSDMap physicsParms = null;
  302. OSDMap map = (OSDMap)meshOsd;
  303. if (map.ContainsKey("physics_shape"))
  304. physicsParms = (OSDMap)map["physics_shape"]; // old asset format
  305. else if (map.ContainsKey("physics_mesh"))
  306. physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
  307. if (physicsParms == null)
  308. {
  309. m_log.WarnFormat("[MESH]: No recognized physics mesh found in mesh asset for {0}", primName);
  310. return false;
  311. }
  312. int physOffset = physicsParms["offset"].AsInteger() + (int)start;
  313. int physSize = physicsParms["size"].AsInteger();
  314. if (physOffset < 0 || physSize == 0)
  315. return false; // no mesh data in asset
  316. OSD decodedMeshOsd = new OSD();
  317. byte[] meshBytes = new byte[physSize];
  318. System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
  319. // byte[] decompressed = new byte[physSize * 5];
  320. try
  321. {
  322. using (MemoryStream inMs = new MemoryStream(meshBytes))
  323. {
  324. using (MemoryStream outMs = new MemoryStream())
  325. {
  326. using (ZOutputStream zOut = new ZOutputStream(outMs))
  327. {
  328. byte[] readBuffer = new byte[2048];
  329. int readLen = 0;
  330. while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
  331. {
  332. zOut.Write(readBuffer, 0, readLen);
  333. }
  334. zOut.Flush();
  335. outMs.Seek(0, SeekOrigin.Begin);
  336. byte[] decompressedBuf = outMs.GetBuffer();
  337. decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
  338. }
  339. }
  340. }
  341. }
  342. catch (Exception e)
  343. {
  344. m_log.Error("[MESH]: exception decoding physical mesh: " + e.ToString());
  345. return false;
  346. }
  347. OSDArray decodedMeshOsdArray = null;
  348. // physics_shape is an array of OSDMaps, one for each submesh
  349. if (decodedMeshOsd is OSDArray)
  350. {
  351. // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
  352. decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
  353. foreach (OSD subMeshOsd in decodedMeshOsdArray)
  354. {
  355. if (subMeshOsd is OSDMap)
  356. AddSubMesh(subMeshOsd as OSDMap, size, coords, faces);
  357. }
  358. }
  359. }
  360. return true;
  361. }
  362. /// <summary>
  363. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  364. /// </summary>
  365. /// <param name="primName"></param>
  366. /// <param name="primShape"></param>
  367. /// <param name="size"></param>
  368. /// <param name="lod"></param>
  369. /// <param name="coords">Coords are added to this list by the method.</param>
  370. /// <param name="faces">Faces are added to this list by the method.</param>
  371. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  372. private bool GenerateCoordsAndFacesFromPrimSculptData(
  373. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  374. {
  375. coords = new List<Coord>();
  376. faces = new List<Face>();
  377. PrimMesher.SculptMesh sculptMesh;
  378. Image idata = null;
  379. string decodedSculptFileName = "";
  380. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  381. {
  382. decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
  383. try
  384. {
  385. if (File.Exists(decodedSculptFileName))
  386. {
  387. idata = Image.FromFile(decodedSculptFileName);
  388. }
  389. }
  390. catch (Exception e)
  391. {
  392. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  393. }
  394. //if (idata != null)
  395. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  396. }
  397. if (idata == null)
  398. {
  399. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  400. return false;
  401. try
  402. {
  403. OpenMetaverse.Imaging.ManagedImage unusedData;
  404. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
  405. if (idata == null)
  406. {
  407. // In some cases it seems that the decode can return a null bitmap without throwing
  408. // an exception
  409. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  410. return false;
  411. }
  412. unusedData = null;
  413. //idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData);
  414. if (cacheSculptMaps)
  415. {
  416. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  417. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  418. }
  419. }
  420. catch (DllNotFoundException)
  421. {
  422. 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!");
  423. return false;
  424. }
  425. catch (IndexOutOfRangeException)
  426. {
  427. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  428. return false;
  429. }
  430. catch (Exception ex)
  431. {
  432. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  433. return false;
  434. }
  435. }
  436. PrimMesher.SculptMesh.SculptType sculptType;
  437. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  438. {
  439. case OpenMetaverse.SculptType.Cylinder:
  440. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  441. break;
  442. case OpenMetaverse.SculptType.Plane:
  443. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  444. break;
  445. case OpenMetaverse.SculptType.Torus:
  446. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  447. break;
  448. case OpenMetaverse.SculptType.Sphere:
  449. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  450. break;
  451. default:
  452. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  453. break;
  454. }
  455. bool mirror = ((primShape.SculptType & 128) != 0);
  456. bool invert = ((primShape.SculptType & 64) != 0);
  457. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  458. idata.Dispose();
  459. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  460. sculptMesh.Scale(size.X, size.Y, size.Z);
  461. coords = sculptMesh.coords;
  462. faces = sculptMesh.faces;
  463. return true;
  464. }
  465. /// <summary>
  466. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  467. /// </summary>
  468. /// <param name="primName"></param>
  469. /// <param name="primShape"></param>
  470. /// <param name="size"></param>
  471. /// <param name="coords">Coords are added to this list by the method.</param>
  472. /// <param name="faces">Faces are added to this list by the method.</param>
  473. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  474. private bool GenerateCoordsAndFacesFromPrimShapeData(
  475. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  476. {
  477. PrimMesh primMesh;
  478. coords = new List<Coord>();
  479. faces = new List<Face>();
  480. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  481. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  482. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  483. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  484. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  485. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  486. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  487. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  488. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  489. if (profileHollow > 0.95f)
  490. profileHollow = 0.95f;
  491. int sides = 4;
  492. LevelOfDetail iLOD = (LevelOfDetail)lod;
  493. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  494. sides = 3;
  495. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  496. {
  497. switch (iLOD)
  498. {
  499. case LevelOfDetail.High: sides = 24; break;
  500. case LevelOfDetail.Medium: sides = 12; break;
  501. case LevelOfDetail.Low: sides = 6; break;
  502. case LevelOfDetail.VeryLow: sides = 3; break;
  503. default: sides = 24; break;
  504. }
  505. }
  506. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  507. { // half circle, prim is a sphere
  508. switch (iLOD)
  509. {
  510. case LevelOfDetail.High: sides = 24; break;
  511. case LevelOfDetail.Medium: sides = 12; break;
  512. case LevelOfDetail.Low: sides = 6; break;
  513. case LevelOfDetail.VeryLow: sides = 3; break;
  514. default: sides = 24; break;
  515. }
  516. profileBegin = 0.5f * profileBegin + 0.5f;
  517. profileEnd = 0.5f * profileEnd + 0.5f;
  518. }
  519. int hollowSides = sides;
  520. if (primShape.HollowShape == HollowShape.Circle)
  521. {
  522. switch (iLOD)
  523. {
  524. case LevelOfDetail.High: hollowSides = 24; break;
  525. case LevelOfDetail.Medium: hollowSides = 12; break;
  526. case LevelOfDetail.Low: hollowSides = 6; break;
  527. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  528. default: hollowSides = 24; break;
  529. }
  530. }
  531. else if (primShape.HollowShape == HollowShape.Square)
  532. hollowSides = 4;
  533. else if (primShape.HollowShape == HollowShape.Triangle)
  534. hollowSides = 3;
  535. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  536. if (primMesh.errorMessage != null)
  537. if (primMesh.errorMessage.Length > 0)
  538. m_log.Error("[ERROR] " + primMesh.errorMessage);
  539. primMesh.topShearX = pathShearX;
  540. primMesh.topShearY = pathShearY;
  541. primMesh.pathCutBegin = pathBegin;
  542. primMesh.pathCutEnd = pathEnd;
  543. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  544. {
  545. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  546. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  547. primMesh.taperX = pathScaleX;
  548. primMesh.taperY = pathScaleY;
  549. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  550. {
  551. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  552. if (profileBegin < 0.0f) profileBegin = 0.0f;
  553. if (profileEnd > 1.0f) profileEnd = 1.0f;
  554. }
  555. #if SPAM
  556. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  557. #endif
  558. try
  559. {
  560. primMesh.ExtrudeLinear();
  561. }
  562. catch (Exception ex)
  563. {
  564. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  565. return false;
  566. }
  567. }
  568. else
  569. {
  570. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  571. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  572. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  573. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  574. primMesh.skew = 0.01f * primShape.PathSkew;
  575. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  576. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  577. primMesh.taperX = primShape.PathTaperX * 0.01f;
  578. primMesh.taperY = primShape.PathTaperY * 0.01f;
  579. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  580. {
  581. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  582. if (profileBegin < 0.0f) profileBegin = 0.0f;
  583. if (profileEnd > 1.0f) profileEnd = 1.0f;
  584. }
  585. #if SPAM
  586. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  587. #endif
  588. try
  589. {
  590. primMesh.ExtrudeCircular();
  591. }
  592. catch (Exception ex)
  593. {
  594. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  595. return false;
  596. }
  597. }
  598. primMesh.DumpRaw(baseDir, primName, "primMesh");
  599. primMesh.Scale(size.X, size.Y, size.Z);
  600. coords = primMesh.coords;
  601. faces = primMesh.faces;
  602. return true;
  603. }
  604. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  605. {
  606. return CreateMesh(primName, primShape, size, lod, false);
  607. }
  608. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  609. {
  610. #if SPAM
  611. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  612. #endif
  613. Mesh mesh = null;
  614. ulong key = 0;
  615. // If this mesh has been created already, return it instead of creating another copy
  616. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  617. key = primShape.GetMeshKey(size, lod);
  618. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  619. return mesh;
  620. if (size.X < 0.01f) size.X = 0.01f;
  621. if (size.Y < 0.01f) size.Y = 0.01f;
  622. if (size.Z < 0.01f) size.Z = 0.01f;
  623. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  624. if (mesh != null)
  625. {
  626. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  627. {
  628. #if SPAM
  629. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  630. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  631. #endif
  632. mesh = CreateBoundingBoxMesh(mesh);
  633. mesh.DumpRaw(baseDir, primName, "Z extruded");
  634. }
  635. // trim the vertex and triangle lists to free up memory
  636. mesh.TrimExcess();
  637. m_uniqueMeshes.Add(key, mesh);
  638. }
  639. return mesh;
  640. }
  641. }
  642. }