ObjData.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  1.  using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Text.RegularExpressions;
  5. namespace VertexAnimationTools_30{
  6. public partial class ObjData {
  7. #region UMESHVERTICES
  8. public class UMeshVertex {
  9. public int ThisIdx;
  10. public PositionVertex Position;
  11. public NormalVertex Normal;
  12. public MapVertex UV;
  13. public BindInfo Bi;
  14. public override bool Equals(object obj) {
  15. UMeshVertex other = (UMeshVertex)obj;
  16. return Position == other.Position && Normal == other.Normal && UV == other.UV;
  17. }
  18. public override int GetHashCode() {
  19. if (UV == null) {
  20. return Position.GetHashCode() + Normal.GetHashCode();
  21. } else {
  22. return Position.GetHashCode() + Normal.GetHashCode() + UV.GetHashCode();
  23. }
  24. }
  25. public void Bind (BindingHelper bh) {
  26. PFU result = new PFU();
  27. result.P = Position.Value;
  28. result.F = Normal.Value;
  29. result.U = UV.Tangent;
  30. bh.Bind(result, ref Bi);
  31. }
  32. }
  33. public class UMeshVerticesList {
  34. Dictionary<UMeshVertex, int> itemsDict = new Dictionary<UMeshVertex, int>();
  35. List<UMeshVertex> items = new List<UMeshVertex>();
  36. public int Count {
  37. get {
  38. return items.Count;
  39. }
  40. }
  41. public UMeshVertex this[int idx] {
  42. get {
  43. return items[idx];
  44. }
  45. }
  46. public UMeshVertex this[PositionVertex position, MapVertex mapVertex, NormalVertex normalVertex] {
  47. get {
  48. UMeshVertex newItem = new UMeshVertex();
  49. int idx = items.Count;
  50. newItem.ThisIdx = items.Count;
  51. newItem.Position = position;
  52. newItem.Normal = normalVertex;
  53. newItem.UV = mapVertex;
  54. int findedIdx = -1;
  55. if (itemsDict.TryGetValue(newItem, out findedIdx)) {
  56. return items[findedIdx];
  57. } else {
  58. itemsDict.Add(newItem, idx);
  59. items.Add(newItem);
  60. return newItem;
  61. }
  62. }
  63. }
  64. }
  65. #endregion
  66. #region NORMALS
  67. public class NormalVertex {
  68. public Vector3 Value;
  69. public float AO;
  70. public bool IsInnerAO;
  71. public int SmoothingGroup;
  72. public PositionVertex Position;
  73. HashSet<AdjacentPolygon> AdjacentPolygons = new HashSet<AdjacentPolygon>();
  74. public AdjacentPolygon[] aAdjacentPolygons;
  75. public List<NormalVertex> AdjacentNormals = new List<NormalVertex>();
  76. public float Cavity;
  77. public float AdjacentMult;
  78. public NormalVertex(int smoothingGroup, PositionVertex posVert) {
  79. Value = Vector3.zero;
  80. SmoothingGroup = smoothingGroup;
  81. Position = posVert;
  82. }
  83. public void Link ( Polygon p ) {
  84. AdjacentPolygon ap = new AdjacentPolygon(p);
  85. AdjacentPolygons.Add(ap);
  86. }
  87. public void OnPostBuild() {
  88. aAdjacentPolygons = new AdjacentPolygon[AdjacentPolygons.Count];
  89. AdjacentPolygons.CopyTo(aAdjacentPolygons);
  90. for (int a = 0; a < aAdjacentPolygons.Length; a++) {
  91. AdjacentNormals.Add(aAdjacentPolygons[a].polygon.GetNextNormal(this));
  92. }
  93. AdjacentMult = 1f / (float)AdjacentNormals.Count;
  94. }
  95. public void CalcAdjacentAreaMults() {
  96. float areaSumm = 0;
  97. for (int a = 0; a < aAdjacentPolygons.Length; a++) {
  98. areaSumm += aAdjacentPolygons[a].polygon.Area;
  99. }
  100. for (int a = 0; a < aAdjacentPolygons.Length; a++) {
  101. aAdjacentPolygons[a].AreaMult = aAdjacentPolygons[a].polygon.Area / areaSumm;
  102. }
  103. }
  104. public void CalcNormal() {
  105. Value = Vector3.zero;
  106. for (int a = 0; a < aAdjacentPolygons.Length; a++) {
  107. Value += aAdjacentPolygons[a].polygon.Normal;
  108. }
  109. //Value.Normalize();
  110. float num = Vector3.Magnitude(Value);
  111. if (num > 1E-05) {
  112. Value /= num;
  113. } else {
  114. //Debug.Log("Zero norm");
  115. for (int e = 0; e < AdjacentNormals.Count; e++) {
  116. Value += (Position.Value - AdjacentNormals[e].Position.Value);
  117. }
  118. Value.Normalize();
  119. }
  120. }
  121. public override bool Equals(object obj) {
  122. NormalVertex other = (NormalVertex)obj;
  123. if (other == null) {
  124. return false;
  125. }
  126. return SmoothingGroup == other.SmoothingGroup && Position == other.Position;
  127. }
  128. public override int GetHashCode() {
  129. return Position.GetHashCode() ^ SmoothingGroup;
  130. }
  131. public void PrintInfo() {
  132. float checkAreaSumm = 0;
  133. foreach (AdjacentPolygon p in AdjacentPolygons) {
  134. checkAreaSumm += p.AreaMult;
  135. }
  136. Debug.LogFormat("Normal Vertex adjacent polygons count {0}, checkAreaSumm:{1}", AdjacentPolygons.Count, checkAreaSumm);
  137. }
  138. }
  139. [System.Serializable]
  140. public class NormalsList {
  141. List<NormalVertex> items = new List<NormalVertex>();
  142. Dictionary<NormalVertex, int> itemsDict = new Dictionary<NormalVertex, int>();
  143. public NormalVertex this[PositionVertex posVertex, int sg] {
  144. get {
  145. NormalVertex newNormal = new NormalVertex(sg, posVertex);
  146. int findedIdx = -1;
  147. if (itemsDict.TryGetValue(newNormal, out findedIdx)) {
  148. return items[findedIdx];
  149. }
  150. itemsDict.Add(newNormal, items.Count);
  151. items.Add(newNormal);
  152. return newNormal;
  153. }
  154. }
  155. public int Count {
  156. get {
  157. return items.Count;
  158. }
  159. }
  160. public NormalVertex this[int idx] {
  161. get {
  162. return items[idx];
  163. }
  164. }
  165. }
  166. #endregion
  167. #region MAPVERTEX
  168. public class MapVertex {
  169. public UMeshVertex UMV;
  170. public Vector2 Value;
  171. HashSet<Polygon> AdjacentPolygons = new HashSet<Polygon>();
  172. Polygon[] aAdjacentPolygons;
  173. public Vector3 Tangent;
  174. public float TangentW;
  175. public MapVertex(Vector2 uv) {
  176. Value = uv;
  177. }
  178. public void Link(Polygon p, UMeshVertex umv) {
  179. AdjacentPolygons.Add(p);
  180. UMV = umv;
  181. }
  182. public void OnPostBuild() {
  183. aAdjacentPolygons = new Polygon[AdjacentPolygons.Count];
  184. AdjacentPolygons.CopyTo(aAdjacentPolygons);
  185. }
  186. public void PrintInfo() {
  187. Debug.LogFormat(" AdjacentPolygons.count{0} ", AdjacentPolygons.Count);
  188. }
  189. public void CalcTangent() {
  190. //Debug.LogFormat("CalcTangent() aAdjacentPolygons.Length{0} ParentNormal not null :{1}", aAdjacentPolygons.Length, ParentNormal!=null);
  191. Vector3 rTangent = Vector3.zero;
  192. for (int i = 0; i < aAdjacentPolygons.Length; i++) {
  193. rTangent += aAdjacentPolygons[i].Tangent;
  194. }
  195. Tangent = Vector3.Cross(Vector3.Cross(UMV.Normal.Value, rTangent), UMV.Normal.Value);
  196. Tangent.Normalize();
  197. }
  198. }
  199. public class MapVerticesList {
  200. List<MapVertex> objmvs = new List<MapVertex>();
  201. Dictionary<PositionVertex, MapVertex> forgedMvs = new Dictionary<PositionVertex, MapVertex>();
  202. public void AddObjMV(Vector2 uv) {
  203. objmvs.Add(new MapVertex(uv));
  204. }
  205. public MapVertex this[PositionVertex pv, int objMvIdx] {
  206. get {
  207. if (objMvIdx >= 0) {
  208. return objmvs[objMvIdx];
  209. }
  210. MapVertex mv = null;
  211. if (forgedMvs.TryGetValue(pv, out mv)) {
  212. return mv;
  213. }
  214. mv = new MapVertex(pv.BindPos);
  215. forgedMvs.Add(pv, mv);
  216. return mv;
  217. }
  218. }
  219. public IEnumerable<MapVertex> AllMapVerts() {
  220. for (int i = 0; i<objmvs.Count; i++) {
  221. yield return objmvs[i];
  222. }
  223. foreach (KeyValuePair<PositionVertex, MapVertex> mv in forgedMvs) {
  224. yield return mv.Value;
  225. }
  226. }
  227. public void PrintInfo(bool detailed ) {
  228. string result = string.Format("objmvs: {0} forgedMvs:{1}", objmvs.Count, forgedMvs.Count);
  229. Debug.Log(result);
  230. if (detailed) {
  231. foreach (MapVertex mv in AllMapVerts()) {
  232. Debug.LogFormat("mv:{0}", mv.Value);
  233. }
  234. }
  235. }
  236. public int Count {
  237. get {
  238. return objmvs.Count + forgedMvs.Count;
  239. }
  240. }
  241. }
  242. #endregion
  243. #region FACE
  244. public class Face {
  245. public int Idx;
  246. public UMeshVertex Va;
  247. public UMeshVertex Vb;
  248. public UMeshVertex Vc;
  249. public Polygon ParentPolygon;
  250. public float TangentT;
  251. public float TangentW;
  252. public float Sign;
  253. public Vector3 Normal;
  254. public Vector3 Tangent;
  255. public Vector3 Center;
  256. public float Area;
  257. bool isParallel;
  258. public float tv;
  259. public Face(int idx, UMeshVertex va, UMeshVertex vb, UMeshVertex vc, Polygon p) {
  260. Idx = idx;
  261. ParentPolygon = p;
  262. Va = va;
  263. Vb = vb;
  264. Vc = vc;
  265. Vector2 _0 = Va.UV.Value;
  266. Vector2 _1 = Vb.UV.Value;
  267. Vector2 _2 = Vc.UV.Value;
  268. Vector2 ab = _1 - _0;
  269. Vector2 ac = _2 - _0;
  270. TangentW = -Mathf.Sign(Vector2.Dot(ac, new Vector2(ab.y, -ab.x)));
  271. if (Mathf.Approximately(_1.y, _2.y)) {
  272. isParallel = true;
  273. Sign = Mathf.Sign(_2.x - _1.x);
  274. } else {
  275. isParallel = false;
  276. tv = (_0.y - _1.y) / (_2.y - _1.y);
  277. float _x = Mathf.LerpUnclamped(_1.x, _2.x, tv);
  278. Sign = _0.x < _x ? 1 : -1;
  279. }
  280. //
  281. //if(Mathf.Approximately(uvB.y, uvC.y)){
  282. // TangentT = -Mathf.Abs(uvB.x - uvC.x) * 1000f;
  283. // Sign = Mathf.Sign(uvB.x - uvC.x);
  284. // } else {
  285. // TangentT = Extension.InverseLerpUnclamped(uvB.y, uvC.y, uvA.y);
  286. // Sign = ((uvB.y > uvC.y) ? -1 : 1) * TangentW;
  287. //}
  288. }
  289. public void Update() {
  290. Normal = GetNormal();
  291. Tangent = GetTangent();
  292. Center = GetCenter();
  293. Area = GetArea();
  294. }
  295. //public void UpdateTangents(Vector3[] mvertices) {
  296. // Vector3 _0 = mvertices[face.v0];
  297. // Vector3 _1 = mvertices[face.v1];
  298. // Vector3 _2 = mvertices[face.v2];
  299. // if (isParallel) {
  300. // tangent = ((_2 - _1) * sign);
  301. // } else {
  302. // Vector3 pointOn12 = Vector3.LerpUnclamped(_1, _2, tv);
  303. // tangent = (pointOn12 - _0) * sign;
  304. // }
  305. //}
  306. Vector3 GetTangent() {
  307. Vector3 _0 = Va.Position.Value;
  308. Vector3 _1 = Vb.Position.Value;
  309. Vector3 _2 = Vc.Position.Value;
  310. if (isParallel) {
  311. return ((_2 - _1) * Sign);
  312. } else {
  313. Vector3 pointOn12 = Vector3.LerpUnclamped(_1, _2, tv);
  314. return (pointOn12 - _0) * Sign;
  315. }
  316. }
  317. //Vector3 GetTangent() {
  318. // Vector3 a = Va.Position.Value;
  319. // Vector3 b = Vb.Position.Value;
  320. // Vector3 c = Vc.Position.Value;
  321. // return (((b + (c - b) * TangentT) - a) * Sign).normalized;
  322. //}
  323. Vector3 GetNormal() {
  324. Vector3 ab = (Vb.Position.Value - Va.Position.Value);
  325. Vector3 ac = (Vc.Position.Value - Va.Position.Value);
  326. return Vector3.Cross(ab*100, ac*100).normalized;
  327. }
  328. float GetArea() {
  329. return Vector3.Cross( (Va.Position.Value - Vb.Position.Value)*100, (Va.Position.Value - Vc.Position.Value)*100).magnitude * 0.005f;
  330. }
  331. Vector3 GetCenter() {
  332. return Va.Position.Value / 3f + Vb.Position.Value / 3f + Vc.Position.Value / 3f;
  333. }
  334. public Matrix4x4 TM {
  335. get {
  336. float div = 1f / 3f;
  337. Vector3 a = Va.Position.Value;
  338. Vector3 b = Vb.Position.Value;
  339. Vector3 c = Vc.Position.Value;
  340. Vector3 na = Va.Normal.Value;
  341. Vector3 nb = Vb.Normal.Value;
  342. Vector3 nc = Vc.Normal.Value;
  343. Vector3 trisCenter = (a + b + c) * div;
  344. Vector3 averageUp = (na + nb + nc) * div;
  345. Vector3 xDir = a - trisCenter;
  346. Vector3 zDir = b - trisCenter;
  347. Matrix4x4 res = Matrix4x4.identity;
  348. res.SetColumn(0, (Vector4)xDir);
  349. res.SetColumn(1, (Vector4)averageUp);
  350. res.SetColumn(2, (Vector4)zDir);
  351. res.SetColumn(3, trisCenter);
  352. res[15] = 1;
  353. return res;
  354. }
  355. }
  356. }
  357. #endregion
  358. #region POSITIONVERTEX
  359. public class PositionVertex {
  360. public Vector3 BindPos;
  361. public Vector3 Value;
  362. public HashSet<AdjacentPolygon> AdjacentPolygons = new HashSet<AdjacentPolygon>();
  363. //public List<Polygon> AdjacentPolygons = new List<Polygon>();
  364. //public List<float> AdjacentAreaMults;
  365. public bool IsInner;
  366. public float InnerAO;
  367. public PositionVertex(Vector3 pos) {
  368. Value = pos;
  369. BindPos = pos;
  370. }
  371. public void Link(Polygon poly ) {
  372. AdjacentPolygons.Add(new AdjacentPolygon(poly));
  373. }
  374. public void CalcAdjacentAreaMults() {
  375. float areaSumm = 0;
  376. foreach (AdjacentPolygon ap in AdjacentPolygons) {
  377. areaSumm += ap.polygon.Area;
  378. }
  379. foreach (AdjacentPolygon ap in AdjacentPolygons) {
  380. ap.AreaMult = ap.polygon.Area / areaSumm;
  381. }
  382. }
  383. }
  384. #endregion
  385. #region POLYGON
  386. public class Polygon {
  387. public int SmoothingGroup;
  388. public Vector3 Normal;
  389. public Vector3 Tangent;
  390. public Vector3 Center;
  391. public float Area;
  392. public List<UMeshVertex> corners = new List<UMeshVertex>();
  393. public float AO;
  394. public float InnerAO;
  395. public float Cavity;
  396. public float FacesMult;
  397. public float CornersMult;
  398. public List<Face> Faces = new List<Face>();
  399. public Polygon(int sg) {
  400. SmoothingGroup = sg;
  401. }
  402. public void BuildTriangles(List<Face> allFaces, List<int> submeshTrisList, bool flipNormals) {
  403. if (flipNormals) {
  404. if (corners.Count > 4) {
  405. Vector3[] cornerPosition = new Vector3[corners.Count];
  406. for (int c = 0; c < corners.Count; c++) {
  407. cornerPosition[c] = corners[c].Position.Value;
  408. }
  409. PolygonTriangulator pt = new PolygonTriangulator(cornerPosition);
  410. int trisCount = pt.trianglesIndeces.Count / 3;
  411. for (int t = 0; t < trisCount; t++) {
  412. UMeshVertex c0 = corners[pt.trianglesIndeces[t * 3 + 2]];
  413. UMeshVertex c1 = corners[pt.trianglesIndeces[t * 3 + 1]];
  414. UMeshVertex c2 = corners[pt.trianglesIndeces[t * 3]];
  415. submeshTrisList.Add(c0.ThisIdx);
  416. submeshTrisList.Add(c1.ThisIdx);
  417. submeshTrisList.Add(c2.ThisIdx);
  418. Face face = new Face(allFaces.Count, c0, c1, c2, this);
  419. allFaces.Add(face);
  420. Faces.Add(face);
  421. }
  422. } else {
  423. for (int c = 1; c < corners.Count - 1; c++) {
  424. submeshTrisList.Add(corners[c + 1].ThisIdx);
  425. submeshTrisList.Add(corners[c].ThisIdx);
  426. submeshTrisList.Add(corners[0].ThisIdx);
  427. Face face = new Face(allFaces.Count, corners[c + 1], corners[c], corners[0], this);
  428. allFaces.Add(face);
  429. Faces.Add(face);
  430. }
  431. }
  432. } else {
  433. if (corners.Count > 4) {
  434. Vector3[] cornerPosition = new Vector3[corners.Count];
  435. for (int c = 0; c < corners.Count; c++) {
  436. cornerPosition[c] = corners[c].Position.Value;
  437. }
  438. PolygonTriangulator pt = new PolygonTriangulator(cornerPosition);
  439. int trisCount = pt.trianglesIndeces.Count / 3;
  440. for (int t = 0; t < trisCount; t++) {
  441. UMeshVertex c0 = corners[pt.trianglesIndeces[t * 3]];
  442. UMeshVertex c1 = corners[pt.trianglesIndeces[t * 3 + 1]];
  443. UMeshVertex c2 = corners[pt.trianglesIndeces[t * 3 + 2]];
  444. submeshTrisList.Add(c0.ThisIdx);
  445. submeshTrisList.Add(c1.ThisIdx);
  446. submeshTrisList.Add(c2.ThisIdx);
  447. Face face = new Face(allFaces.Count, c0, c1, c2, this);
  448. allFaces.Add(face);
  449. Faces.Add(face);
  450. }
  451. } else {
  452. for (int c = 1; c < corners.Count - 1; c++) {
  453. submeshTrisList.Add(corners[0].ThisIdx);
  454. submeshTrisList.Add(corners[c].ThisIdx);
  455. submeshTrisList.Add(corners[c + 1].ThisIdx);
  456. Face face = new Face(allFaces.Count, corners[0], corners[c], corners[c + 1], this);
  457. allFaces.Add(face);
  458. Faces.Add(face);
  459. }
  460. }
  461. }
  462. FacesMult = 1f / (float)Faces.Count;
  463. CornersMult = 1f / (float)corners.Count;
  464. float tangentW = 0;
  465. for (int f = 0; f < Faces.Count; f++) {
  466. tangentW += Faces[f].TangentW;
  467. }
  468. tangentW = tangentW >= 0 ? 1f : -1f;
  469. for (int c = 0; c < corners.Count; c++) {
  470. corners[c].UV.TangentW = tangentW;
  471. }
  472. }
  473. public void Update(NormalsRecalculationModeEnum normalMode) {
  474. for (int f = 0; f < Faces.Count; f++) {
  475. Faces[f].Update();
  476. }
  477. Tangent = Vector3.zero;
  478. Normal = Vector3.zero;
  479. Center = Vector3.zero;
  480. Area = 0;
  481. if (normalMode == NormalsRecalculationModeEnum.Default) {
  482. for (int f = 0; f < Faces.Count; f++) {
  483. Face face = Faces[f];
  484. Tangent += face.Tangent;
  485. Normal += face.Normal;
  486. Area += face.Area;
  487. Center += face.Center * FacesMult;
  488. }
  489. } else {
  490. for (int f = 0; f < Faces.Count; f++) {
  491. Face face = Faces[f];
  492. Tangent += face.Tangent * face.Area;
  493. Normal += face.Normal * face.Area;
  494. Area += face.Area;
  495. Center += face.Center * FacesMult;
  496. }
  497. }
  498. }
  499. public NormalVertex GetNextNormal(NormalVertex nv) {
  500. int nvIdx = -1;
  501. for (int c = 0; c < corners.Count; c++) {
  502. if (corners[c].Normal == nv) {
  503. nvIdx = c;
  504. break;
  505. }
  506. }
  507. return corners[(nvIdx + 1) % corners.Count].Normal;
  508. }
  509. public Matrix4x4 TM {
  510. get {
  511. return Matrix4x4.TRS(Center, Quaternion.LookRotation(Normal, corners[0].Position.Value - Center), Vector3.one);
  512. }
  513. }
  514. public bool ContainsTris(int trisIdx) {
  515. for (int t = 0; t < Faces.Count; t++) {
  516. if (Faces[t].Idx == trisIdx) {
  517. return true;
  518. }
  519. }
  520. return false;
  521. }
  522. }
  523. public class AdjacentPolygon {
  524. public Polygon polygon;
  525. public float AreaMult;
  526. public AdjacentPolygon(Polygon p) {
  527. polygon = p;
  528. AreaMult = 0;
  529. }
  530. public override bool Equals(object obj) {
  531. return ((AdjacentPolygon)obj).polygon == this.polygon;
  532. }
  533. public override int GetHashCode() {
  534. return this.polygon.GetHashCode();
  535. }
  536. }
  537. #endregion
  538. #region SUBMESHES
  539. public class SubMesh {
  540. public string MaterialName;
  541. public List<int> TrisIndeces = new List<int>();
  542. public List<Polygon> Polygons = new List<Polygon>();
  543. public SubMesh(string materialName) {
  544. MaterialName = materialName;
  545. }
  546. public void AddPolygon(Polygon p) {
  547. Polygons.Add(p);
  548. }
  549. }
  550. public class SubMeshesList {
  551. List<SubMesh> items = new List<SubMesh>();
  552. public SubMesh Current = new SubMesh("Default submesh");
  553. public void SetCurrent(string materialName) {
  554. for (int s = 0; s < items.Count; s++) {
  555. if (items[s].MaterialName == materialName) {
  556. Current = items[s];
  557. return;
  558. }
  559. }
  560. SubMesh newItem = new SubMesh(materialName);
  561. items.Add(newItem);
  562. Current = newItem;
  563. }
  564. public int Count {
  565. get {
  566. if (items.Count == 0) {
  567. return 1;
  568. } else {
  569. return items.Count;
  570. }
  571. }
  572. }
  573. public SubMesh this[int idx] {
  574. get {
  575. if (items.Count == 0) {
  576. return Current;
  577. } else {
  578. return items[idx];
  579. }
  580. }
  581. }
  582. public void RemoveUnused() {
  583. List<SubMesh> unused = new List<SubMesh>();
  584. for (int s = items.Count - 1; s >= 0; s--) {
  585. if (items[s].Polygons.Count == 0) {
  586. unused.Add(items[s]);
  587. }
  588. }
  589. for (int i = 0; i < unused.Count; i++) {
  590. items.Remove(unused[i]);
  591. }
  592. }
  593. public string[] GetNames() {
  594. string[] result = new string[items.Count];
  595. for (int i = 0; i < items.Count; i++) {
  596. result[i] = items[i].MaterialName;
  597. }
  598. return result;
  599. }
  600. public List<Polygon> GetAllPolygons() {
  601. List<Polygon> result = new List<Polygon>();
  602. for (int i = 0; i<Count; i++) {
  603. result.AddRange(this[i].Polygons);
  604. }
  605. return result;
  606. }
  607. }
  608. #endregion
  609. #region POLYGONTRIANGULATOR
  610. public class PolygonTriangulator {
  611. public class Corner {
  612. public int SourceIdx;
  613. public Vector3 WorldPoint;
  614. public Vector2 PolygonSpacePoint;
  615. public float Angle;
  616. public bool Used;
  617. public Corner(Vector3 worldPoint, int idx) {
  618. WorldPoint = worldPoint;
  619. SourceIdx = idx;
  620. }
  621. }
  622. List<Corner> corners;
  623. public List<int> trianglesIndeces;
  624. Corner minAngleCorner = null;
  625. public PolygonTriangulator(Vector3[] cornerPositions) {
  626. corners = new List<Corner>();
  627. for (int i = 0; i < cornerPositions.Length; i++) {
  628. corners.Add(new Corner(cornerPositions[i], i));
  629. }
  630. Vector3 PolyCenter = Vector3.zero;
  631. float mult = 1f / (float)corners.Count;
  632. for (int i = 0; i < corners.Count; i++) {
  633. PolyCenter += corners[i].WorldPoint * mult;
  634. }
  635. Vector3 PolyNormal = Vector3.zero;
  636. for (int i = 0; i < corners.Count; i++) {
  637. int nexti = (i + 1) % (corners.Count - 1);
  638. Vector3 dirI = corners[i].WorldPoint - PolyCenter;
  639. Vector3 nextI = corners[nexti].WorldPoint - PolyCenter;
  640. PolyNormal += Vector3.Cross(dirI, nextI);
  641. }
  642. PolyNormal.Normalize();
  643. Vector3 PolyUp = (corners[0].WorldPoint - PolyCenter).normalized;
  644. Matrix4x4 PolygonTM = Matrix4x4.TRS(PolyCenter, Quaternion.LookRotation(PolyNormal, PolyUp), Vector3.one);
  645. Matrix4x4 polygonTMInverted = PolygonTM.inverse;
  646. for (int c = 0; c < corners.Count; c++) {
  647. corners[c].PolygonSpacePoint = polygonTMInverted.MultiplyPoint3x4(corners[c].WorldPoint);
  648. }
  649. trianglesIndeces = new List<int>();
  650. int trisCount = corners.Count - 2;
  651. for (int c = 0; c < trisCount; c++) {
  652. UpdateAngles();
  653. int i = corners.IndexOf(minAngleCorner);
  654. int previ = i - 1;
  655. if (previ < 0) {
  656. previ = corners.Count - 1;
  657. }
  658. int nexti = i + 1;
  659. if (nexti >= corners.Count) {
  660. nexti = 0;
  661. }
  662. trianglesIndeces.Add(corners[i].SourceIdx);
  663. trianglesIndeces.Add(corners[nexti].SourceIdx);
  664. trianglesIndeces.Add(corners[previ].SourceIdx);
  665. if (minAngleCorner != null) {
  666. corners.Remove(minAngleCorner);
  667. }
  668. }
  669. }
  670. void UpdateAngles() {
  671. float minAngle = float.MaxValue;
  672. for (int i = 0; i < corners.Count; i++) {
  673. int previ = i - 1;
  674. if (previ < 0) {
  675. previ = corners.Count - 1;
  676. }
  677. int nexti = i + 1;
  678. if (nexti >= corners.Count) {
  679. nexti = 0;
  680. }
  681. Vector2 prevDir = corners[i].PolygonSpacePoint - corners[previ].PolygonSpacePoint;
  682. float prevAngle = Mathf.Atan2(prevDir.y, prevDir.x);
  683. Vector2 nextDir = corners[nexti].PolygonSpacePoint - corners[i].PolygonSpacePoint;
  684. float nextAngle = Mathf.Atan2(nextDir.y, nextDir.x);
  685. corners[i].Angle = 180 - Mathf.DeltaAngle(prevAngle * Mathf.Rad2Deg, nextAngle * Mathf.Rad2Deg);
  686. if (corners[i].Angle < minAngle) {
  687. if (IsTriangleAllow(previ, i, nexti)) {
  688. minAngleCorner = corners[i];
  689. minAngle = corners[i].Angle;
  690. }
  691. }
  692. }
  693. }
  694. bool IsTriangleAllow(int idxa, int idxb, int idxc) {
  695. Triangle2d tris = new Triangle2d(corners[idxa].PolygonSpacePoint, corners[idxb].PolygonSpacePoint, corners[idxc].PolygonSpacePoint);
  696. Vector3 bary = new Vector3();
  697. for (int c = 0; c < corners.Count; c++) {
  698. if (c == idxa || c == idxb || c == idxc) {
  699. continue;
  700. }
  701. if (tris.PointTest(corners[c].PolygonSpacePoint, ref bary)) {
  702. return false;
  703. }
  704. }
  705. return true;
  706. }
  707. }
  708. #endregion
  709. #region TRIANGLE2D
  710. public struct Triangle2d {
  711. public Vector2 a;
  712. public Vector2 b;
  713. public Vector2 c;
  714. Vector2 v0;
  715. Vector2 v1;
  716. float dot00;
  717. float dot01;
  718. float dot11;
  719. float invDenom;
  720. public Triangle2d(Vector2 _a, Vector2 _b, Vector2 _c) {
  721. a = _a;
  722. b = _b;
  723. c = _c;
  724. v0 = c - a;
  725. v1 = b - a;
  726. dot00 = Vector2.Dot(v0, v0);
  727. dot01 = Vector2.Dot(v0, v1);
  728. dot11 = Vector2.Dot(v1, v1);
  729. invDenom = 1f / (dot00 * dot11 - dot01 * dot01);
  730. }
  731. public bool PointTest(Vector2 p, ref Vector3 bary) {
  732. Vector2 v2 = p - a;
  733. float dot02 = Vector2.Dot(v0, v2);
  734. float dot12 = Vector2.Dot(v1, v2);
  735. bary.z = (dot11 * dot02 - dot01 * dot12) * invDenom; // u
  736. bary.y = (dot00 * dot12 - dot01 * dot02) * invDenom; // v
  737. bary.x = 1f - (bary.z + bary.y);
  738. return (bary.z >= 0) && (bary.y >= 0) && (bary.z + bary.y < 1f);
  739. }
  740. }
  741. #endregion
  742. public enum SmoothingGroupImportModeEnum {
  743. FromObjFile,
  744. FlatShading,
  745. SmoothAll
  746. }
  747. public enum NormalsRecalculationModeEnum {
  748. Default,
  749. Weighted,
  750. }
  751. public enum ObjLineIdEnum{
  752. v,
  753. vt,
  754. f,
  755. s,
  756. s_off,
  757. usemtl,
  758. other
  759. }
  760. public string Name;
  761. public bool FlipNormals;
  762. public bool CalculateNormals;
  763. public bool ImportUV;
  764. public bool CalculateTangents;
  765. public SmoothingGroupImportModeEnum SmoothingGroupsMode;
  766. public NormalsRecalculationModeEnum NormalsRecalculationMode;
  767. public Vector3[] UM_vertices;
  768. Vector2[] UM_uv;
  769. public Vector3[] UM_normals;
  770. public Vector3[] UM_v3tangents;
  771. public Color[] UM_colors;
  772. public Vector4[] UM_v4tangents;
  773. public Bounds UM_Bounds;
  774. public Vector3[] VerticesToSet;
  775. public List<Face> AllFaces = new List<Face>();
  776. public SubMeshesList SubMeshes;
  777. public List<PositionVertex> Vertices = new List<PositionVertex>();
  778. public NormalsList Normals = new NormalsList();
  779. public MapVerticesList mapVertices = new MapVerticesList();
  780. Vector3[] bindVerts ;
  781. Vector3[] bindNormals;
  782. Vector3[] bindTangents;
  783. #if UNITY_2017_3_OR_NEWER
  784. public UnityEngine.Rendering.IndexFormat IndexFormat = UnityEngine.Rendering.IndexFormat.UInt16;
  785. #endif
  786. public UMeshVerticesList UnityVertices = new UMeshVerticesList();
  787. public List <Polygon> AllPolygons = new List<Polygon>();
  788. Mesh refMesh;
  789. string[] subString;
  790. System.IO.TextReader objFile;
  791. int currentSmoothingGroup = 0;
  792. bool offSGMode = false;
  793. int offSGcounter = 1;
  794. char[] spaceSeparator = @" ".ToCharArray();
  795. float objFileLength;
  796. public System.Diagnostics.Stopwatch BuildSW;
  797. public System.Diagnostics.Stopwatch ApplySW;
  798. FaceLineParser fplp = new FaceLineParser();
  799. public ObjData(string path){
  800. System.IO.FileInfo fi = new System.IO.FileInfo(path);
  801. if(!fi.Exists){
  802. Debug.LogErrorFormat("obj file {0} not found", path);
  803. }
  804. Name = fi.Name;
  805. objFile = System.IO.File.OpenText(path);
  806. BuildSW = new System.Diagnostics.Stopwatch();
  807. ApplySW = new System.Diagnostics.Stopwatch();
  808. }
  809. public void Build() {
  810. BuildSW.Reset();
  811. BuildSW.Start();
  812. refMesh = new Mesh();
  813. #if UNITY_2017_3_OR_NEWER
  814. refMesh.indexFormat = IndexFormat;
  815. #endif
  816. SubMeshes = new SubMeshesList();
  817. while (true) {
  818. string str = objFile.ReadLine();
  819. if (str == null) {
  820. #if UNITY_WSA
  821. objFile.Dispose();
  822. #else
  823. objFile.Close();
  824. #endif
  825. break;
  826. }
  827. ObjLineIdEnum lineId = GetObjLineId(str);
  828. if (lineId == ObjLineIdEnum.vt) {
  829. subString = str.Split(spaceSeparator, System.StringSplitOptions.RemoveEmptyEntries);
  830. Vector2 uv = new Vector2(ToFloat(subString[1]), ToFloat(subString[2]));
  831. mapVertices.AddObjMV (uv) ;
  832. } else if (lineId == ObjLineIdEnum.v) {
  833. subString = str.Split(spaceSeparator, System.StringSplitOptions.RemoveEmptyEntries);
  834. Vector3 defaultPos = new Vector3(ToFloat(subString[1]), ToFloat(subString[2]), ToFloat(subString[3]));
  835. Vertices.Add(new PositionVertex(defaultPos));
  836. } else if (lineId == ObjLineIdEnum.usemtl) {
  837. SubMeshes.SetCurrent(str.Remove(0, 7));
  838. } else if (lineId == ObjLineIdEnum.s_off) {
  839. offSGMode = true;
  840. } else if (lineId == ObjLineIdEnum.s) {
  841. offSGMode = false;
  842. currentSmoothingGroup = ToInt(str.Remove(0, 2));
  843. } else if (lineId == ObjLineIdEnum.f) {
  844. int sg = currentSmoothingGroup;
  845. if (SmoothingGroupsMode == SmoothingGroupImportModeEnum.SmoothAll) {
  846. sg = 0;
  847. } else if (SmoothingGroupsMode == SmoothingGroupImportModeEnum.FlatShading || offSGMode) {
  848. sg = -offSGcounter;
  849. offSGcounter++;
  850. }
  851. fplp.Parse(str);
  852. Polygon poly = new Polygon(sg);
  853. for (int c = 0; c < fplp.corners.Count; c++) {
  854. PositionVertex pv = Vertices[fplp.corners[c].VertIdx];
  855. MapVertex mv = mapVertices[pv, fplp.corners[c].UvIdx];
  856. NormalVertex nv = Normals[pv, sg];
  857. UMeshVertex umv = UnityVertices[pv, mv, nv];
  858. pv.Link(poly);
  859. mv.Link(poly, umv);
  860. nv.Link( poly );
  861. poly.corners.Add(umv);
  862. }
  863. SubMeshes.Current.AddPolygon(poly);
  864. }
  865. }
  866. AllPolygons = SubMeshes.GetAllPolygons();
  867. foreach (MapVertex mv in mapVertices.AllMapVerts() ) {
  868. mv.OnPostBuild();
  869. }
  870. for (int n = 0; n < Normals.Count; n++) {
  871. Normals[n].OnPostBuild();
  872. }
  873. UM_vertices = new Vector3[UnityVertices.Count];
  874. UM_normals = new Vector3[UnityVertices.Count];
  875. UM_v3tangents = new Vector3[UnityVertices.Count];
  876. UM_v4tangents = new Vector4[UnityVertices.Count];
  877. VerticesToSet = new Vector3[Vertices.Count];
  878. for(int v = 0; v<Vertices.Count; v++){
  879. VerticesToSet[v] = Vertices[v].BindPos;
  880. }
  881. refMesh.vertices = UM_vertices;
  882. SubMeshes.RemoveUnused();
  883. refMesh.subMeshCount = SubMeshes.Count;
  884. for(int s = 0; s<SubMeshes.Count; s++){
  885. for(int p = 0; p<SubMeshes[s].Polygons.Count; p++){
  886. SubMeshes[s].Polygons[p].BuildTriangles( AllFaces, SubMeshes[s].TrisIndeces, FlipNormals );
  887. }
  888. refMesh.SetTriangles(SubMeshes[s].TrisIndeces.ToArray(), s);
  889. }
  890. if(ImportUV){
  891. UM_uv = new Vector2[UnityVertices.Count];
  892. for(int v = 0; v<UnityVertices.Count; v++){
  893. UM_uv[v] = UnityVertices[v].UV.Value;
  894. }
  895. refMesh.uv = UM_uv;
  896. if(CalculateNormals){
  897. if(CalculateTangents){
  898. for(int v = 0; v<UM_v4tangents.Length; v++){
  899. UM_v4tangents[v] = new Vector4(0,0,0, UnityVertices[v].UV.TangentW);
  900. }
  901. }
  902. }
  903. }
  904. BuildSW.Stop();
  905. }
  906. public IEnumerable<TaskInfo> BindIE( BindingHelper bh ) {
  907. string tiname = string.Format("Binding {0}", Name);
  908. for (int i = 0; i < UnityVertices.Count; i++) {
  909. UnityVertices[i].Bind(bh);
  910. yield return new TaskInfo(tiname, i/(float)UnityVertices.Count);
  911. }
  912. yield return new TaskInfo(tiname, 1f);
  913. }
  914. public void BindToBh(BindingHelper bh) {
  915. for (int i = 0; i < UnityVertices.Count; i++) {
  916. UnityVertices[i].Bind(bh);
  917. }
  918. }
  919. public void ApplyBinded(BindingHelper bh) {
  920. //Debug.LogFormat("Apply binded od vertices count:{0} bh:{1} UnityVertices.Count:{2}", Vertices.Count, bh, UnityVertices.Count);
  921. for (int i = 0; i<UnityVertices.Count; i++) {
  922. PFU current = UnityVertices[i].Bi.TrisSpace * bh.GetTrisTM(UnityVertices[i].Bi.VidxA, UnityVertices[i].Bi.VidxB, UnityVertices[i].Bi.VidxC, UnityVertices[i].Bi.Bary);
  923. UM_vertices[i] = current.P;
  924. UM_normals[i] = current.F;
  925. UM_v3tangents[i] = current.U;
  926. }
  927. }
  928. public void Apply( bool SwapYZ, float Scale ){
  929. ApplySW.Reset();
  930. ApplySW.Start();
  931. for(int v = 0; v<VerticesToSet.Length; v++){
  932. Vector3 vert = VerticesToSet[v];
  933. if (SwapYZ) {
  934. vert.Set(vert.x, vert.z, vert.y);
  935. }
  936. vert *= Scale;
  937. if (v == 0){
  938. UM_Bounds = new Bounds(vert, Vector3.zero);
  939. } else {
  940. UM_Bounds.Encapsulate( vert );
  941. }
  942. Vertices[v].Value = vert;
  943. }
  944. for(int v = 0; v<UnityVertices.Count; v++){
  945. UM_vertices[v] = UnityVertices[v].Position.Value;
  946. }
  947. if(CalculateNormals){
  948. for(int p = 0; p<AllPolygons.Count; p++){
  949. AllPolygons[p].Update( NormalsRecalculationMode );
  950. }
  951. for( int n = 0; n<Normals.Count; n++ ){
  952. Normals[n].CalcNormal();
  953. }
  954. for(int v = 0; v<UnityVertices.Count; v++){
  955. UM_normals[v] = UnityVertices[v].Normal.Value;
  956. }
  957. }
  958. if (ImportUV && CalculateNormals && CalculateTangents) {
  959. for (int v = 0; v < UnityVertices.Count; v++) {
  960. UnityVertices[v].UV.CalcTangent();
  961. Vector3 tan = UnityVertices[v].UV.Tangent;
  962. UM_v3tangents[v] = tan;
  963. UM_v4tangents[v].x = tan.x;
  964. UM_v4tangents[v].y = tan.y;
  965. UM_v4tangents[v].z = tan.z;
  966. }
  967. }
  968. refMesh.vertices = UM_vertices;
  969. refMesh.normals = UM_normals;
  970. refMesh.bounds = UM_Bounds;
  971. refMesh.tangents = UM_v4tangents;
  972. ApplySW.Stop();
  973. }
  974. public static bool GetObjInfo(string pathToObj, ref string name, ref int vertCount, ref int polygonsCount, ref int submeshesCount ){
  975. name = System.IO.Path.GetFileNameWithoutExtension(pathToObj);
  976. System.IO.TextReader objFile = System.IO.File.OpenText(pathToObj);
  977. List<string> submeshesNames = new List<string>();
  978. while (true){
  979. string str = objFile.ReadLine();
  980. if(str == null) break;
  981. ObjLineIdEnum id = GetObjLineId(str);
  982. if(id == ObjLineIdEnum.v ){
  983. vertCount ++;
  984. } else if( id == ObjLineIdEnum.f ){
  985. polygonsCount ++;
  986. } else if( id == ObjLineIdEnum.usemtl ){
  987. string submeshName = str.Remove(0,7);
  988. if(!submeshesNames.Contains(submeshName)){
  989. submeshesNames.Add(submeshName);
  990. }
  991. }
  992. }
  993. #if UNITY_WSA
  994. objFile.Dispose();
  995. #else
  996. objFile.Close();
  997. #endif
  998. submeshesCount = submeshesNames.Count;
  999. return polygonsCount>0 && vertCount>0;
  1000. }
  1001. public static bool GetObjInfo(string pathToObj, ref int vertCount) {
  1002. System.IO.TextReader objFile = System.IO.File.OpenText(pathToObj);
  1003. while (true) {
  1004. string str = objFile.ReadLine();
  1005. if (str == null) break;
  1006. ObjLineIdEnum id = GetObjLineId(str);
  1007. if (id == ObjLineIdEnum.v) {
  1008. vertCount++;
  1009. }
  1010. }
  1011. #if UNITY_WSA
  1012. objFile.Dispose();
  1013. #else
  1014. objFile.Close();
  1015. #endif
  1016. return vertCount > 0;
  1017. }
  1018. public void SetBindPoseFrameVertices() {
  1019. bindVerts = Extension.Copy( UM_vertices );
  1020. bindNormals = Extension.Copy( UM_normals );
  1021. bindTangents = Extension.Copy( UM_v3tangents );
  1022. }
  1023. public static Vector3[] GetVerticesFromObj(string path , bool swapAxis, float scale) {
  1024. List<Vector3> verticesList = new List<Vector3>();
  1025. System.IO.TextReader objFile = System.IO.File.OpenText(path);
  1026. char[] spaceSeparator = @" ".ToCharArray();
  1027. string[] subString;
  1028. while (true) {
  1029. string str = objFile.ReadLine();
  1030. if (str == null) break;
  1031. ObjLineIdEnum id = GetObjLineId(str);
  1032. if (id == ObjLineIdEnum.v) {
  1033. subString = str.Split(spaceSeparator, System.StringSplitOptions.RemoveEmptyEntries);
  1034. Vector3 defaultPos = new Vector3(ToFloat(subString[1]), ToFloat(subString[2]), ToFloat(subString[3]));
  1035. if (swapAxis) {
  1036. defaultPos.Set(defaultPos.x, defaultPos.z, defaultPos.y);
  1037. }
  1038. defaultPos = defaultPos * scale;
  1039. verticesList.Add(defaultPos);
  1040. }
  1041. }
  1042. #if UNITY_WSA
  1043. objFile.Dispose();
  1044. #else
  1045. objFile.Close();
  1046. #endif
  1047. return verticesList.ToArray();
  1048. }
  1049. public Vector3[] GetPosDeltas() {
  1050. return Extension.Delta(bindVerts, UM_vertices);
  1051. }
  1052. public Vector3[] GetNormsDeltas() {
  1053. return Extension.Delta(bindNormals, UM_normals);
  1054. }
  1055. public Vector3[] GetTansDeltas() {
  1056. return Extension.Delta(bindTangents, UM_v3tangents);
  1057. }
  1058. public static ObjLineIdEnum GetObjLineId (string str){
  1059. char[] chars = str.ToCharArray();
  1060. if(chars.Length<2){
  1061. return ObjLineIdEnum.other;
  1062. }
  1063. if(chars[0]=='v' && chars[1] == ' '){
  1064. return ObjLineIdEnum.v;
  1065. }
  1066. if(chars[0]=='v' && chars[1] == 't'){
  1067. return ObjLineIdEnum.vt;
  1068. }
  1069. if(chars[0]=='f' && chars[1] == ' '){
  1070. return ObjLineIdEnum.f;
  1071. }
  1072. if(chars[0]=='s' && chars[1] == ' '){
  1073. return ObjLineIdEnum.s;
  1074. }
  1075. //usemtl
  1076. if(chars[0]=='u' && chars[1]=='s' && chars[2]=='e' && chars[3]=='m' && chars[4]=='t' && chars[5]=='l' ){
  1077. return ObjLineIdEnum.usemtl;
  1078. }
  1079. if(chars[0]=='s' && chars[1]==' ' && chars[2]=='o' && chars[3]=='f' && chars[4]=='f'){
  1080. return ObjLineIdEnum.s_off;
  1081. }
  1082. return ObjLineIdEnum.other;
  1083. }
  1084. static float ToFloat(string s) {
  1085. return float.Parse(s, System.Globalization.CultureInfo.InvariantCulture );
  1086. }
  1087. int ToInt(string s) {
  1088. int result = 0;
  1089. int.TryParse(s, out result);
  1090. return result;
  1091. }
  1092. public class FaceLineParser {
  1093. public class Corner {
  1094. public int VertIdx = -1;
  1095. public int UvIdx = -1;
  1096. public int NormalIdx = -1;
  1097. public List<char>[] chars = { new List<char>(), new List<char>(), new List<char>(), };
  1098. public int ci;
  1099. public void Parse() {
  1100. if (chars[0].Count > 0) {
  1101. int.TryParse(new string(chars[0].ToArray()), out VertIdx);
  1102. VertIdx--;
  1103. }
  1104. if (chars[1].Count > 0) {
  1105. int.TryParse(new string(chars[1].ToArray()), out UvIdx);
  1106. UvIdx--;
  1107. }
  1108. if (chars[2].Count > 0) {
  1109. int.TryParse(new string(chars[2].ToArray()), out NormalIdx);
  1110. NormalIdx--;
  1111. }
  1112. }
  1113. }
  1114. public List<Corner> corners = new List<Corner>();
  1115. public void Parse(string str) {
  1116. corners.Clear();
  1117. char[] ca = str.ToCharArray();
  1118. Corner current = null;
  1119. for (int i = 2; i<ca.Length; i++) {
  1120. char c = ca[i];
  1121. if (char.IsDigit(c)) {
  1122. if (current == null) {
  1123. current = new Corner();
  1124. }
  1125. current.chars[current.ci].Add(c);
  1126. }
  1127. if (ca[i] == '/') {
  1128. current.ci++;
  1129. continue;
  1130. }
  1131. if (ca[i] == ' ') {
  1132. if (current != null) {
  1133. corners.Add(current);
  1134. current = null;
  1135. }
  1136. continue;
  1137. }
  1138. }
  1139. if (current != null) {
  1140. corners.Add(current);
  1141. }
  1142. for (int c = 0; c<corners.Count; c++) {
  1143. corners[c].Parse();
  1144. }
  1145. }
  1146. public void PrintDebug() {
  1147. string result = string.Format("corners count {0} ", corners.Count);
  1148. for (int i = 0; i<corners.Count; i++) {
  1149. result += string.Format( " {0}/{1}/{2} ", corners[i].VertIdx, corners[i].UvIdx, corners[i].NormalIdx );
  1150. }
  1151. Debug.Log(result);
  1152. }
  1153. }
  1154. public bool CalcVertexColor( VertexColorsSettings settings ) {
  1155. ProjectionSamples ps = Resources.Load<ProjectionSamples>("VertexAnimationTools_ProjectionSamples");
  1156. bool innerOcclusionEnabled = settings.InnerVertexOcclusion && settings.InnerVertexOcclusionAmount > 0;
  1157. bool ambientOcclusionEnabled = settings.AmbientOcclusion && settings.AmbientOcclusionAmount > 0;
  1158. bool cavityEnabled = settings.Cavity && settings.CavityAmount > 0;
  1159. if (!innerOcclusionEnabled && !ambientOcclusionEnabled && !cavityEnabled) {
  1160. return false;
  1161. }
  1162. Vector3[] sphereDirs = ps.SphereSamples[0].Dirs;
  1163. Vector3[] domeDirs = ps.DomeSamples[(int)settings.quality].Dirs;
  1164. RaycastHit hit = new RaycastHit();
  1165. RaycastHit ihit = new RaycastHit();
  1166. Matrix4x4 objTM = settings.go.transform.localToWorldMatrix;
  1167. if (!CalculateNormals) {
  1168. for (int p = 0; p < AllPolygons.Count; p++) {
  1169. AllPolygons[p].Update(NormalsRecalculationMode);
  1170. }
  1171. for (int n = 0; n < Normals.Count; n++) {
  1172. Normals[n].CalcNormal();
  1173. }
  1174. }
  1175. for (int n = 0; n < Normals.Count; n++) {
  1176. Normals[n].CalcAdjacentAreaMults();
  1177. }
  1178. for (int v = 0; v < Vertices.Count; v++) {
  1179. Vertices[v].CalcAdjacentAreaMults();
  1180. }
  1181. #region CAVITY
  1182. if (cavityEnabled) {
  1183. for (int n = 0; n < Normals.Count; n++) {
  1184. ObjData.NormalVertex norm = Normals[n];
  1185. norm.Cavity = 0;
  1186. for (int a = 0; a < norm.AdjacentNormals.Count; a++) {
  1187. Vector3 toanv = (norm.AdjacentNormals[a].Position.Value - norm.Position.Value).normalized;
  1188. float angle = Mathf.InverseLerp(settings.CavityAngleMax, settings.CavityAngleMin, Vector3.Angle(toanv, norm.Value));
  1189. norm.Cavity += angle * norm.AdjacentMult;
  1190. }
  1191. }
  1192. for (int i = 0; i < settings.CavityBlurIterations; i++) {
  1193. for (int p = 0; p < AllPolygons.Count; p++) {
  1194. ObjData.Polygon poly = AllPolygons[p];
  1195. poly.Cavity = 0;
  1196. for (int c = 0; c < poly.corners.Count; c++) {
  1197. poly.Cavity += poly.corners[c].Normal.Cavity * poly.CornersMult;
  1198. }
  1199. }
  1200. for (int n = 0; n < Normals.Count; n++) {
  1201. ObjData.NormalVertex norm = Normals[n];
  1202. float polyCurvature = 0;
  1203. int counter = 0;
  1204. for (int a = 0; a < norm.aAdjacentPolygons.Length; a++) {
  1205. ObjData.AdjacentPolygon p = norm.aAdjacentPolygons[a];
  1206. polyCurvature += p.polygon.Cavity * p.AreaMult;
  1207. counter++;
  1208. }
  1209. norm.Cavity = Mathf.Lerp(norm.Cavity, polyCurvature, settings.CavityBlur);
  1210. }
  1211. }
  1212. }
  1213. #endregion
  1214. if (ambientOcclusionEnabled || innerOcclusionEnabled) {
  1215. #region CREATECOLLIDERS
  1216. GameObject mcGO = new GameObject("mcGO");
  1217. mcGO.transform.position = settings.go.transform.position;
  1218. mcGO.transform.rotation = settings.go.transform.rotation;
  1219. mcGO.transform.localScale = settings.go.transform.localScale;
  1220. MeshCollider mc = mcGO.AddComponent<MeshCollider>();
  1221. mc.sharedMesh = refMesh;
  1222. GameObject imcGO = new GameObject("imcGO");
  1223. imcGO.transform.position = settings.go.transform.position;
  1224. imcGO.transform.rotation = settings.go.transform.rotation;
  1225. imcGO.transform.localScale = settings.go.transform.localScale;
  1226. MeshCollider imc = imcGO.AddComponent<MeshCollider>();
  1227. //INVERT MC
  1228. Mesh inverted = Object.Instantiate(refMesh) as Mesh;
  1229. int[] tris = inverted.triangles;
  1230. for (int t = 0; t < tris.Length; t += 3) {
  1231. int t0 = tris[t + 2];
  1232. int t1 = tris[t + 1];
  1233. int t2 = tris[t];
  1234. tris[t] = t0;
  1235. tris[t + 1] = t1;
  1236. tris[t + 2] = t2;
  1237. }
  1238. inverted.triangles = tris;
  1239. imc.sharedMesh = inverted;
  1240. #endregion
  1241. #region INNERVERTEX
  1242. if (innerOcclusionEnabled) {
  1243. for (int v = 0; v < Vertices.Count; v++) {
  1244. ObjData.PositionVertex vert = Vertices[v];
  1245. Vector3 normal = Vector3.zero;
  1246. foreach (ObjData.AdjacentPolygon ap in vert.AdjacentPolygons) {
  1247. normal += ap.polygon.Normal.normalized * ap.AreaMult;
  1248. }
  1249. Vector3 vertWP = objTM.MultiplyPoint3x4(vert.Value + normal * 0.01f);
  1250. int innerHitCount = 0;
  1251. int outerHitCount = 0;
  1252. vert.InnerAO = 0;
  1253. for (int s = 0; s < sphereDirs.Length; s++) {
  1254. Ray sampleRay = new Ray(vertWP, sphereDirs[s]);
  1255. float dist = float.MaxValue;
  1256. float idist = float.MaxValue;
  1257. if (mc.Raycast(sampleRay, out hit, float.MaxValue)) {
  1258. dist = hit.distance;
  1259. }
  1260. if (imc.Raycast(sampleRay, out ihit, float.MaxValue)) {
  1261. idist = ihit.distance;
  1262. }
  1263. if (idist < dist) {
  1264. innerHitCount++;
  1265. } else {
  1266. outerHitCount++;
  1267. }
  1268. if (innerHitCount >= outerHitCount) {
  1269. vert.IsInner = true;
  1270. vert.InnerAO = 1;
  1271. }
  1272. }
  1273. }
  1274. for (int i = 0; i < settings.InnerVertexOcclusionBlurIterations; i++) {
  1275. for (int p = 0; p < AllPolygons.Count; p++) {
  1276. ObjData.Polygon poly = AllPolygons[p];
  1277. poly.InnerAO = 0;
  1278. for (int c = 0; c < poly.corners.Count; c++) {
  1279. poly.InnerAO += poly.corners[c].Position.InnerAO * poly.CornersMult;
  1280. }
  1281. }
  1282. for (int n = 0; n < Vertices.Count; n++) {
  1283. ObjData.PositionVertex vert = Vertices[n];
  1284. float ainnerAO = 0;
  1285. foreach (ObjData.AdjacentPolygon ap in vert.AdjacentPolygons) {
  1286. ainnerAO += ap.polygon.InnerAO * ap.AreaMult;
  1287. }
  1288. vert.InnerAO = Mathf.Lerp(vert.InnerAO, ainnerAO, settings.InnerVertexOcclusionBlur);
  1289. }
  1290. }
  1291. }
  1292. #endregion
  1293. #region AmbientOcclusion
  1294. if (ambientOcclusionEnabled) {
  1295. float samplesMult = 1f / (float)domeDirs.Length;
  1296. for (int p = 0; p < AllPolygons.Count; p++) {
  1297. ObjData.Polygon poly = AllPolygons[p];
  1298. poly.AO = 0;
  1299. Matrix4x4 ptm = objTM * poly.TM;
  1300. for (int i = 0; i < domeDirs.Length; i++) {
  1301. Vector3 dir = ptm.MultiplyVector(domeDirs[i]);
  1302. Ray sampleRay = new Ray((Vector3)ptm.GetColumn(3), dir);
  1303. if (mc.Raycast(sampleRay, out hit, settings.AmbientOcclusionRadius)) {
  1304. poly.AO += Mathf.InverseLerp(settings.AmbientOcclusionRadius, 0, hit.distance) * samplesMult;
  1305. }
  1306. }
  1307. }
  1308. for (int n = 0; n < Normals.Count; n++) {
  1309. ObjData.NormalVertex norm = Normals[n];
  1310. for (int a = 0; a < norm.aAdjacentPolygons.Length; a++) {
  1311. norm.AO += norm.aAdjacentPolygons[a].polygon.AO * norm.aAdjacentPolygons[a].AreaMult;
  1312. }
  1313. }
  1314. for (int i = 0; i < settings.AmbientOcclusionBlurIterations; i++) {
  1315. for (int p = 0; p < AllPolygons.Count; p++) {
  1316. ObjData.Polygon poly = AllPolygons[p];
  1317. poly.AO = 0;
  1318. for (int c = 0; c < poly.corners.Count; c++) {
  1319. poly.AO += poly.corners[c].Normal.AO * poly.CornersMult;
  1320. }
  1321. }
  1322. for (int n = 0; n < Normals.Count; n++) {
  1323. ObjData.NormalVertex norm = Normals[n];
  1324. float nao = 0;
  1325. for (int a = 0; a < norm.aAdjacentPolygons.Length; a++) {
  1326. nao += norm.aAdjacentPolygons[a].polygon.AO * norm.aAdjacentPolygons[a].AreaMult;
  1327. }
  1328. norm.AO = Mathf.LerpUnclamped(norm.AO, nao, settings.AmbientOcclusionBlur);
  1329. }
  1330. }
  1331. }
  1332. #endregion
  1333. Object.DestroyImmediate(mcGO);
  1334. Object.DestroyImmediate(imcGO);
  1335. }
  1336. UM_colors = new Color[UnityVertices.Count];
  1337. for (int v = 0; v < UnityVertices.Count; v++) {
  1338. UM_colors[v].a = 1f - (UnityVertices[v].Normal.Cavity * settings.CavityAmount);
  1339. UM_colors[v].a -= (UnityVertices[v].Position.InnerAO * settings.InnerVertexOcclusionAmount);
  1340. UM_colors[v].a -= (UnityVertices[v].Normal.AO * settings.AmbientOcclusionAmount);
  1341. }
  1342. return true;
  1343. }
  1344. [System.Serializable]
  1345. public struct VertexColorsSettings {
  1346. public GameObject go;
  1347. public ProjectionQualityEnum quality;
  1348. public bool Cavity;
  1349. public float CavityAmount;
  1350. public float CavityAngleMin;
  1351. public float CavityAngleMax;
  1352. public float CavityBlur;
  1353. public int CavityBlurIterations;
  1354. public bool InnerVertexOcclusion;
  1355. public float InnerVertexOcclusionAmount;
  1356. public float InnerVertexOcclusionBlur;
  1357. public int InnerVertexOcclusionBlurIterations;
  1358. public bool AmbientOcclusion;
  1359. public float AmbientOcclusionAmount;
  1360. public float AmbientOcclusionRadius;
  1361. public float AmbientOcclusionBlur;
  1362. public int AmbientOcclusionBlurIterations;
  1363. public bool AnyEnabled {
  1364. get {
  1365. return InnerVertexOcclusion || Cavity || AmbientOcclusion;
  1366. }
  1367. }
  1368. public VertexColorsSettings(bool enableAO) {
  1369. go = null;
  1370. Cavity = false;
  1371. CavityAmount = 1;
  1372. CavityAngleMin = 70f;
  1373. CavityAngleMax = 90f;
  1374. CavityBlur = 1f;
  1375. CavityBlurIterations = 1;
  1376. InnerVertexOcclusion = false;
  1377. InnerVertexOcclusionAmount = 0.75f;
  1378. InnerVertexOcclusionBlur = 1;
  1379. InnerVertexOcclusionBlurIterations = 1;
  1380. AmbientOcclusion = enableAO;
  1381. AmbientOcclusionAmount = 1;
  1382. AmbientOcclusionRadius = 1;
  1383. AmbientOcclusionBlur = 1;
  1384. AmbientOcclusionBlurIterations = 1;
  1385. quality = ProjectionQualityEnum.Medium;
  1386. }
  1387. }
  1388. public Mesh Snapshot {
  1389. get {
  1390. return Object.Instantiate(refMesh) as Mesh;
  1391. }
  1392. }
  1393. public void CopyTo(Mesh m) {
  1394. m.Clear();
  1395. #if UNITY_2017_3_OR_NEWER
  1396. m.indexFormat = IndexFormat;
  1397. #endif
  1398. m.vertices = UM_vertices;
  1399. m.subMeshCount = refMesh.subMeshCount;
  1400. for (int i = 0; i<refMesh.subMeshCount; i++) {
  1401. m.SetTriangles(refMesh.GetTriangles(i), i );
  1402. }
  1403. m.bounds = refMesh.bounds;
  1404. m.colors = refMesh.colors;
  1405. m.uv = refMesh.uv;
  1406. m.normals = UM_normals;
  1407. m.tangents = UM_v4tangents;
  1408. //Debug.LogFormat("od copy indexformat:{0} buildsw:{1} applysw:{2}", m.indexFormat, BuildSW.ElapsedMilliseconds, ApplySW.ElapsedMilliseconds);
  1409. }
  1410. }
  1411. }