1
0

Meshmerizer.cs 31 KB

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