// Use this for initialization public static Mesh FileToMesh(string filePath) { meshStruct newMesh = createMeshStruct(filePath); populateMeshStruct(ref newMesh); Vector3[] newVerts = new Vector3[newMesh.faceData.Length]; Vector2[] newUVs = new Vector2[newMesh.faceData.Length]; Vector3[] newNormals = new Vector3[newMesh.faceData.Length]; int i = 0; /* The following foreach loops through the facedata and assigns the appropriate vertex, uv, or normal * for the appropriate Unity mesh array. */ foreach (Vector3 v in newMesh.faceData) { newVerts[i] = newMesh.vertices[(int)v.x - 1]; if (v.y >= 1) newUVs[i] = newMesh.uv[(int)v.y - 1]; if (v.z >= 1) newNormals[i] = newMesh.normals[(int)v.z - 1]; i++; } Mesh mesh = new Mesh(); mesh.vertices = newVerts; mesh.uv = newUVs; mesh.normals = newNormals; mesh.triangles = newMesh.triangles; mesh.RecalculateBounds(); mesh.Optimize(); return mesh; }
public static void CreateConvexHull(ConvexHullShape shape, Mesh mesh) { ShapeHull hull = new ShapeHull(shape); hull.BuildHull(shape.Margin); List<UnityEngine.Vector3> verts = new List<UnityEngine.Vector3>(); List<int> tris = new List<int>(); //int vertexCount = hull.NumVertices; UIntArray indices = hull.Indices; Vector3Array points = hull.Vertices; for (int i = 0; i < indices.Count; i+=3) { verts.Add(points[(int)indices[i]].ToUnity()); verts.Add(points[(int)indices[i+1]].ToUnity()); verts.Add(points[(int)indices[i+2]].ToUnity()); tris.Add(i); tris.Add(i + 1); tris.Add(i + 2); } mesh.vertices = verts.ToArray(); mesh.triangles = tris.ToArray(); mesh.RecalculateBounds(); mesh.RecalculateNormals(); }
private void AddFace(WaterFace face) { // TODO if ((face.Flags & WaterFlags.Visible) != WaterFlags.Visible) return; var obj = Instantiate(WaterPrefab); obj.transform.SetParent(transform); var mid = obj.transform.position = face.Vertices.Aggregate(Vector3.zero, (s, x) => s + x.Position) / face.Vertices.Length; obj.name = string.Format("WaterFace ({0})", mid); var mesh = new Mesh(); mesh.vertices = face.Vertices.Select(x => x.Position - mid).ToArray(); mesh.normals = face.Vertices.Select(x => Vector3.up).ToArray(); var indices = new int[(face.Vertices.Length - 2) * 3]; for (var i = 0; i < face.Vertices.Length - 2; ++i) { var flip = i & 1; indices[i * 3 + 0] = i + 1 - flip; indices[i * 3 + 1] = i + 0 + flip; indices[i * 3 + 2] = i + 2; } mesh.SetIndices(indices, MeshTopology.Triangles, 0); obj.GetComponent<MeshFilter>().sharedMesh = mesh; }
public override void ModifyMesh(Mesh mesh) { if (this.IsActive()) { List<UIVertex> stream = new List<UIVertex>(); using (VertexHelper helper = new VertexHelper(mesh)) { helper.GetUIVertexStream(stream); } int num = stream.Count * 5; if (stream.Capacity < num) { stream.Capacity = num; } int start = 0; int count = stream.Count; base.ApplyShadowZeroAlloc(stream, base.effectColor, start, stream.Count, base.effectDistance.x, base.effectDistance.y); start = count; count = stream.Count; base.ApplyShadowZeroAlloc(stream, base.effectColor, start, stream.Count, base.effectDistance.x, -base.effectDistance.y); start = count; count = stream.Count; base.ApplyShadowZeroAlloc(stream, base.effectColor, start, stream.Count, -base.effectDistance.x, base.effectDistance.y); start = count; count = stream.Count; base.ApplyShadowZeroAlloc(stream, base.effectColor, start, stream.Count, -base.effectDistance.x, -base.effectDistance.y); using (VertexHelper helper2 = new VertexHelper()) { helper2.AddUIVertexTriangleStream(stream); helper2.FillMesh(mesh); } } }
//todo this really needs to be threaded, some meshes are quite large public static Mesh CloneMesh(Mesh mesh) { Mesh newmesh = new Mesh(); newmesh.name = mesh.name; var newverts = new Vector3[mesh.vertices.Length]; for (int i = 0; i < mesh.vertices.Length; i++) { var vertex = mesh.vertices[i]; Vector3 v = qRotateX * vertex; newverts[i] = qRotateZ * v; } newmesh.vertices = newverts; newmesh.subMeshCount = mesh.subMeshCount; for (int i = 0; i < mesh.subMeshCount; i++) { int[] triangles = mesh.GetTriangles(i); newmesh.SetTriangles(triangles, i); } newmesh.uv = mesh.uv; newmesh.uv2 = mesh.uv2; newmesh.uv2 = mesh.uv2; newmesh.normals = mesh.normals; newmesh.colors = mesh.colors; newmesh.tangents = mesh.tangents; return newmesh; }
/// <summary> /// Centers the pivot of the mesh /// </summary> /// <returns> /// The offset the geometry was moved by to center the pivot. /// </returns> /// <param name='mesh'> /// Mesh /// </param> public static Vector3 Center (Mesh mesh) { mesh.RecalculateBounds (); Vector3 diff = mesh.bounds.center; PivotTools.Move (mesh, diff); return diff; }
public static Mesh GetSmoothVersionOf(Mesh sourceMesh, int iterations = 1, float alpha = 0, float beta = .5f) { var workingMesh = sourceMesh.Clone(); for (int i = 0; i < iterations; i++) workingMesh.vertices = HCFilter(sourceMesh.vertices, workingMesh.vertices, workingMesh.triangles, alpha, beta); return workingMesh; }
public static Mesh GenerateWireCube() { float l = 0.5f; Vector3[] vertices = new Vector3[] { new Vector3( l, l, l), new Vector3( l, l,-l), new Vector3(-l, l,-l), new Vector3(-l, l, l), new Vector3( l,-l, l), new Vector3( l,-l,-l), new Vector3(-l,-l,-l), new Vector3(-l,-l, l), }; int[] indices = new int[] { 0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7, }; Mesh r = new Mesh(); r.name = "Wire Cube"; r.vertices = vertices; r.SetIndices(indices, MeshTopology.Lines, 0); return r; }
public static void CombineMeshes(Queue<CombineInstance> items , byte area , InputGeometryCompiler compiler) { const int MaxTris = 65000; List<CombineInstance> combineInstancesPart = new List<CombineInstance>(); byte[] areas = NMGen.CreateAreaBuffer(MaxTris, area); while (items.Count != 0) { int vertCount = 0; while (items.Count > 0 && (vertCount + items.Peek().mesh.vertexCount < MaxTris)) { vertCount += items.Peek().mesh.vertexCount; combineInstancesPart.Add(items.Dequeue()); } Mesh meshPart = new Mesh(); meshPart.CombineMeshes(combineInstancesPart.ToArray(), true, true); compiler.AddTriangles(meshPart.vertices, meshPart.vertexCount , meshPart.triangles, areas, meshPart.triangles.Length / 3); Object.DestroyImmediate(meshPart); combineInstancesPart.Clear(); } }
protected override void ReadChunk(byte[] chunkData, ref Mesh mesh) { //number of bytes that are for uv1 var uv1Count = BitConverter.ToInt32(chunkData, 0); //number of bytes that are for uv2 var uv2Count = BitConverter.ToInt32(chunkData, sizeof(int)); var uv1Floats = new float[uv1Count/sizeof (float)]; var uv2Floats = new float[uv2Count/sizeof (float)]; Buffer.BlockCopy(chunkData, HEADER_SIZE, uv1Floats, 0, uv1Count); Buffer.BlockCopy(chunkData, HEADER_SIZE + uv1Count, uv2Floats, 0, uv2Count); var uv1 = new Vector2[uv1Floats.Length/2]; var uv2 = new Vector2[uv2Floats.Length/2]; for (int i = 0; i < uv1Floats.Length; i += 2) { uv1[i / 2] = new Vector2(uv1Floats[i], uv1Floats[i + 1]); } for (int i = 0; i < uv2Floats.Length; i += 2) { uv2[i / 2] = new Vector2(uv2Floats[i], uv2Floats[i + 1]); } //mesh.uv1 and mesh.uv2 are the second uv set mesh.uv = uv1; mesh.uv1 = uv2; }
/// <summary> /// cut mesh by plane /// </summary> /// <param name="mesh">mesh to cut</param> /// <param name="meshTransform">transformation of the mesh</param> /// <param name="plane">cutting plane</param> /// <param name="triangulateHoles">flag for triangulation of holes</param> /// <param name="crossSectionVertexColor">this color will be assigned to cross section, valid only for vertex color shaders</param> /// <param name="crossUV">uv mapping area for cross section</param> /// <param name="allowOpenMesh">allow cutting of open mesh</param> /// <returns>processing time</returns> public float Cut(Mesh mesh, Transform meshTransform, Math.Plane plane, bool triangulateHoles, bool allowOpenMesh, ref List<CutterMesh> meshes, Color crossSectionVertexColor, Vector4 crossUV) { this.crossSectionVertexColour = crossSectionVertexColor; this.crossSectionUV = crossUV; return Cut(mesh, meshTransform, plane, triangulateHoles, allowOpenMesh, ref meshes); }
public static bool Export(string folder, string filename, Mesh mesh, ExportMaterial[] textures, bool copyTextures) { exportMesh = mesh; exportTextures = textures; targetFolder = folder; targetName = filename; _copyTextures = copyTextures; if(folder.Contains(" ")) { EditorUtility.DisplayDialog("Filename Error","The filename can't contain spaces","I'm sorry"); return false; } if(filename.Contains(" ")) { EditorUtility.DisplayDialog("Filename Error","The filename can't contain spaces","I'm sorry"); return false; } /*if (!CreateTargetFolder()) { Debug.LogError("There was a problem with the destination folder"); return false; }*/ MeshToFile(targetFolder, targetName); exportMesh = null; exportTextures = null; return true; }
public static Mesh CreateMesh(Vector2 dimensions) { Mesh mesh = new Mesh(); Vector3[] vertices = new Vector3[] { new Vector3(dimensions.x, dimensions.y, 0), new Vector3(dimensions.x, -dimensions.y, 0), new Vector3(-dimensions.x, dimensions.y, 0), new Vector3(-dimensions.x, -dimensions.y, 0), }; Vector2[] uv = new Vector2[] { new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 1), new Vector2(0, 0), }; int[] triangles = new int[] { 0, 1, 2, 2, 1, 3, }; mesh.vertices = vertices; mesh.uv = uv; mesh.triangles = triangles; mesh.RecalculateNormals(); return mesh; }
protected override void WriteChunk(out byte[] chunkData, Mesh mesh) { //mesh.uv1 and mesh.uv2 are the second uv set var uv1 = mesh.uv; var uv2 = mesh.uv1; var chunkLength = uv1.Length*UV_SIZE + uv2.Length*UV_SIZE + HEADER_SIZE; chunkData = new byte[chunkLength]; var uv1Floats = new float[uv1.Length*2]; var uv2Floats = new float[uv2.Length*2]; for (var i = 0; i < uv1Floats.Length; i += 2) { var vert = uv1[i / 2]; uv1Floats[i] = vert.x; uv1Floats[i + 1] = vert.y; } for (var i = 0; i < uv2Floats.Length; i += 2) { var vert = uv2[i / 2]; uv2Floats[i] = vert.x; uv2Floats[i + 1] = vert.y; } //do actual writing //byte counts var uv1Count = uv1Floats.Length*sizeof (float); var uv2Count = uv2Floats.Length*sizeof (float); //header CopyBytes(uv1Count, chunkData, 0); CopyBytes(uv2Count, chunkData, sizeof(int)); //data Buffer.BlockCopy(uv1Floats, 0, chunkData, HEADER_SIZE, uv1Count); Buffer.BlockCopy(uv2Floats, 0, chunkData, HEADER_SIZE + uv1Count, uv2Count); }
static Vector2[] GenerateProportionalUVs( Vector3[] vertices, Mesh original ) { Vector2[] result = new Vector2[ vertices.Length ]; int vertexIndexToCalculateDiff = 0; for ( int i = 1; i < original.vertexCount; i++ ) { if ( original.vertices[ 0 ].x != original.vertices[ i ].x && original.vertices[ 0 ].y != original.vertices[ i ].y ) { vertexIndexToCalculateDiff = i; break; } } if ( vertexIndexToCalculateDiff == 0 ) { throw new System.Exception( "Couldn't find vertexes with different x and y coordinates!" ); } Vector3 twoFirstVerticesDiff = original.vertices[ vertexIndexToCalculateDiff ] - original.vertices[ 0 ]; Vector2 twoFirstUVsDiff = original.uv[ vertexIndexToCalculateDiff ] - original.uv[ 0 ]; Vector2 distanceToUVMap = new Vector2(); distanceToUVMap.x = twoFirstUVsDiff.x / twoFirstVerticesDiff.x; distanceToUVMap.y = twoFirstUVsDiff.y / twoFirstVerticesDiff.y; for ( int i = 0; i < vertices.Length; i++ ) { result[ i ] = ( vertices[ i ] - original.vertices[ 0 ] ); result[ i ] = new Vector2( result[ i ].x * distanceToUVMap.x, result[ i ].y * distanceToUVMap.y ); result[ i ] += original.uv[ 0 ]; } return result; }
// todo : make extensdion method public static Mesh JoinMeshes( Mesh first, Mesh second ) { int newVertLength = first.vertices.Length + second.vertices.Length; int newTriLength = first.triangles.Length + second.triangles.Length; Vector3[] newVerts = new Vector3[ newVertLength ]; Vector2[] newUVs = new Vector2[ newVertLength ]; int[] newTris = new int[ newTriLength ]; for ( int v=0; v<newVertLength; v++ ) { if ( v == second.vertices.Length ) break; newVerts[ v ] = v >= first.vertices.Length ? second.vertices[ v ] : first.vertices[ v ]; newUVs[ v ] = v >= first.vertices.Length ? second.uv[ v ] : first.uv[ v ]; } for ( int t=0; t<newTriLength; t++ ) { if ( t == second.triangles.Length ) break; newTris[ t ] = t >= first.triangles.Length ? second.triangles[ t ] : first.triangles[ t ]; } Mesh newMesh = new Mesh(); newMesh.vertices = newVerts; newMesh.uv = newUVs; newMesh.triangles = newTris; newMesh.RecalculateNormals(); newMesh.RecalculateBounds(); return newMesh; }
//////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Build(MenuState pMenuState, IItemVisualSettings pSettings, float pAngle0, float pAngle1) { vMenuState = pMenuState; vSettings = (ItemVisualSettingsStandard)pSettings; vAngle0 = pAngle0; vAngle1 = pAngle1; vMeshSteps = (int)Math.Round(Math.Max(2, (vAngle1-vAngle0)/Math.PI*60)); //// vBackground = new GameObject("Background"); vBackground.transform.SetParent(gameObject.transform, false); vBackground.AddComponent<MeshRenderer>(); MeshFilter bgFilt = vBackground.AddComponent<MeshFilter>(); vBackgroundMesh = bgFilt.mesh; BuildMesh(vBackgroundMesh); Materials.SetMeshColor(vBackgroundMesh, Color.clear); //// var labelObj = new GameObject("Label"); labelObj.transform.SetParent(gameObject.transform, false); labelObj.transform.localPosition = new Vector3(0, 0, InnerRadius); labelObj.transform.localRotation = Quaternion.FromToRotation(Vector3.back, Vector3.right); labelObj.transform.localScale = new Vector3((vMenuState.IsOnLeftSide ? 1 : -1), 1, 1); vLabel = labelObj.AddComponent<UiLabel>(); vLabel.AlignLeft = vMenuState.IsOnLeftSide; }
// public void Assign(Mesh m) { m.vertices = vertices.ToArray(); m.triangles = triangles.ToArray(); m.normals = normals.ToArray(); m.uv = uv.ToArray(); }
public override void ModifyMesh(Mesh mesh) { if (this.IsActive() == false) { return; } var list = new List<UIVertex>(); using (var vertexHelper = new VertexHelper(mesh)) { vertexHelper.GetUIVertexStream(list); } this.ModifyVertices(list); // calls the old ModifyVertices which was used on pre 5.2 using (var vertexHelper = new VertexHelper()) { vertexHelper.AddUIVertexTriangleStream(list); vertexHelper.FillMesh(mesh); } }
public static pb_Renderable CreateInstance(Mesh InMesh, Material InMaterial) { pb_Renderable ren = ScriptableObject.CreateInstance<pb_Renderable>(); ren.mesh = InMesh; ren.materials = new Material[] { InMaterial }; return ren; }
/// <summary> /// Sets the pivot to a given Vector3 offset from the center of the Mesh bounds. /// </summary> public static Vector3 Set (Mesh mesh, Vector3 offset) { mesh.RecalculateBounds (); Vector3 diff = mesh.bounds.center - offset; PivotTools.Move (mesh, diff); return diff; }
public static string ExportToString (Mesh mesh, Renderer renderer, bool uselhcoords = true, bool separateSubmeshes = true){ Material[] mats = renderer.sharedMaterials; // Initiation StringBuilder sb = new StringBuilder(); //Header sb.Append("o ").Append("Plane").Append("\n"); foreach(Vector3 v in mesh.vertices) { sb.Append(string.Format("v {0:0.000000} {1:0.000000} {2:0.000000}\n",(uselhcoords?-v.x:v.x),v.y,v.z)); } sb.Append("\n"); foreach(Vector3 v in mesh.normals) { sb.Append(string.Format("vn {0:0.000000} {1:0.000000} {2:0.000000}\n",v.x,v.y,v.z)); } sb.Append("\n"); foreach(Vector3 v in mesh.uv) { sb.Append(string.Format("vt {0:0.000000} {1:0.000000}\n",v.x,v.y)); } for (int material=0; material < mesh.subMeshCount; material ++) { sb.Append("\n"); if (separateSubmeshes){ sb.Append("g ").Append(mats[material].name).Append("\n"); } sb.Append("usemtl ").Append(mats[material].name).Append("\n"); sb.Append("usemap ").Append(mats[material].name).Append("\n"); int[] triangles = mesh.GetTriangles(material); for (int i=0;i<triangles.Length;i+=3) { sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", triangles[(uselhcoords?i+1:i)]+1, triangles[(uselhcoords?i:i+1)]+1, triangles[i+2]+1)); } } return sb.ToString(); }
public static void CalcSoftOcclusion(Mesh mesh) { GameObject gameObject = new GameObject("Test"); gameObject.layer = 29; gameObject.AddComponent<MeshFilter>().mesh = mesh; gameObject.AddComponent<MeshCollider>(); if (TreeAO.directions == null) TreeAO.InitializeDirections(); Vector4[] vector4Array1 = new Vector4[TreeAO.directions.Length]; for (int index = 0; index < TreeAO.directions.Length; ++index) vector4Array1[index] = new Vector4(TreeAO.GetWeight(1, TreeAO.directions[index]), TreeAO.GetWeight(2, TreeAO.directions[index]), TreeAO.GetWeight(3, TreeAO.directions[index]), TreeAO.GetWeight(0, TreeAO.directions[index])); Vector3[] vertices = mesh.vertices; Vector4[] vector4Array2 = new Vector4[vertices.Length]; float num1 = 0.0f; for (int index1 = 0; index1 < vertices.Length; ++index1) { Vector4 zero = Vector4.zero; Vector3 v = gameObject.transform.TransformPoint(vertices[index1]); for (int index2 = 0; index2 < TreeAO.directions.Length; ++index2) { float num2 = Mathf.Pow(0.5f, (float) TreeAO.CountIntersections(v, gameObject.transform.TransformDirection(TreeAO.directions[index2]), 3f)); zero += vector4Array1[index2] * num2; } zero /= (float) TreeAO.directions.Length; num1 += zero.w; vector4Array2[index1] = zero; } float num3 = num1 / (float) vertices.Length; for (int index = 0; index < vertices.Length; ++index) vector4Array2[index].w -= num3; mesh.tangents = vector4Array2; Object.DestroyImmediate((Object) gameObject); }
public void Write(SceneWriter writer, object component) { Component script = component as Component; if (script == null) { throw new Exception(GetType() + " cannot export components of type " + component.GetType()); } MeshFilter[] meshFilters = script.GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length]; for ( int i = 0; i < meshFilters.Length; i++) { combine[i].mesh = meshFilters[i].sharedMesh; combine[i].transform = meshFilters[i].transform.localToWorldMatrix; } Mesh mesh = new Mesh(); mesh.CombineMeshes(combine); MeshRenderer mr = script.GetComponentInChildren<MeshRenderer>(); writer.WriteElement("sharedMaterials", mr.sharedMaterials); writer.WriteElement("triangles", mesh.triangles); writer.WriteElement("vertices", mesh.vertices); //writer.WriteElement("normals", mesh.normals); writer.WriteElement("uv", mesh.uv); Debug.Log(script.name + " batched " + combine.Length + " objects into a mesh of " + (mesh.triangles.Length / 3) + " triangles and " + mesh.vertices.Length + " vertices."); if (mesh.vertices.Length > short.MaxValue) { Debug.LogWarning("BATCHED TOO MANY TRIANGLES!!"); } }
private void CreateTriangles(Color color) { Color[] colors = new Color[3]; for (int c = 0; c < 3; ++c) colors[c] = tileColor; for (int i = 0; i < vertices.Count; ++i) { Vector3 a = vertices[i]; Vector3 b = new Vector3(); if (i == vertices.Count - 1) b = vertices[0]; else b = vertices[i + 1]; Mesh triangle = GenerateTriangle(a, b, centerPoint); //Mesh triangle = GenerateTriangle(a, b, c); GameObject triangleObject = new GameObject("Triangle", typeof(MeshFilter)); triangleObject.GetComponent<MeshFilter>().mesh = triangle; triangleObject.transform.parent = this.transform; Mesh triangleToCenter = new Mesh(); triangleToCenter = GenerateTriangle(b, a, Vector3.zero); GameObject triangleToCenterObject = new GameObject("Triangle", typeof(MeshFilter)); triangleToCenterObject.GetComponent<MeshFilter>().mesh = triangleToCenter; triangleToCenterObject.transform.parent = this.transform; } }
public Mesh CreateMesh() { Mesh m = new Mesh { vertices = Vertices.ToArray(), uv = UV1.ToArray(), uv2 = UV2.ToArray(), triangles = Triangles.ToArray(), colors = Colors.ToArray() }; if(Submeshes.Count > 0) { CombineInstance[] instances = new CombineInstance[Submeshes.Count]; for(int i = 0; i < Submeshes.Count; i++) { CombineInstance ins = new CombineInstance { mesh = Submeshes[i].CreateMesh(), transform = Matrix4x4.identity }; instances[i] = ins; } m.CombineMeshes(instances, false); } m.RecalculateNormals(); m.RecalculateBounds(); m.Optimize(); return m; }
public void Initialize(List<Vector3> verts, bool ocean) { // initialize tileObject = new GameObject("TileObject", typeof(MeshRenderer)); tileMesh = new Mesh(); vertices = verts; plate = -1; // find centerpoint centerPoint = CenterPoint(vertices); //centerPoint = Vector3.zero; tileColor = new Color(UnityEngine.Random.Range(0.0f, 1.0f), UnityEngine.Random.Range(0.0f, 1.0f), UnityEngine.Random.Range(0.0f, 1.0f), 1); // sort points clockwise SortPointsClockwise(centerPoint); // create triangles if (ocean == false) CreateTriangles(tileColor); else CreateTrianglesOcean(); foreach (Transform child in transform) Destroy(child.gameObject); // merge into one mesh UnifyMesh(ref tileMesh); Destroy(tileObject); }
public void Dispose() { if (snapShotMesh != null) UnityEngine.Object.DestroyImmediate(snapShotMesh); snapShotMesh = null; }
/// <summary> /// construct a new bsp tree from unity mesh /// </summary> /// <param name="mesh">unity mesh</param> /// <param name="meshTransform">transformation</param> /// <param name="id">id of the mesh</param> public void Construct(Mesh mesh, Transform meshTransform, int id) { // cache mesh data var trianglesNum = mesh.triangles.Length; var meshTriangles = mesh.triangles; var meshVertices = mesh.vertices; var meshNormals = mesh.normals; var meshUV = mesh.uv; Polygons = new List<CSGPolygon>(trianglesNum/3); for (int i = 0; i < trianglesNum; i+=3) { var id0 = meshTriangles[i]; var id1 = meshTriangles[i + 1]; var id2 = meshTriangles[i + 2]; Polygons.Add(new CSGPolygon(id, new CSGVertex(meshTransform.TransformPoint(meshVertices[id0]), meshTransform.TransformDirection(meshNormals[id0]), meshUV[id0]), new CSGVertex(meshTransform.TransformPoint(meshVertices[id1]), meshTransform.TransformDirection(meshNormals[id1]), meshUV[id1]), new CSGVertex(meshTransform.TransformPoint(meshVertices[id2]), meshTransform.TransformDirection(meshNormals[id2]), meshUV[id2]))); } root = new CSGNode(); root.Build(Polygons); }
protected override void OnPopulateMesh(Mesh toFill) { Texture mainTexture = this.mainTexture; if (mainTexture != null) { Vector4 zero = Vector4.zero; int num = Mathf.RoundToInt(mainTexture.width * this.uvRect.width); int num2 = Mathf.RoundToInt(mainTexture.height * this.uvRect.height); float num3 = ((num & 1) != 0) ? ((float) (num + 1)) : ((float) num); float num4 = ((num2 & 1) != 0) ? ((float) (num2 + 1)) : ((float) num2); zero.x = 0f; zero.y = 0f; zero.z = ((float) num) / num3; zero.w = ((float) num2) / num4; zero.x -= base.rectTransform.pivot.x; zero.y -= base.rectTransform.pivot.y; zero.z -= base.rectTransform.pivot.x; zero.w -= base.rectTransform.pivot.y; zero.x *= base.rectTransform.rect.width; zero.y *= base.rectTransform.rect.height; zero.z *= base.rectTransform.rect.width; zero.w *= base.rectTransform.rect.height; using (VertexHelper helper = new VertexHelper()) { Color color = base.color; helper.AddVert(new Vector3(zero.x, zero.y), color, new Vector2(this.m_UVRect.xMin, this.m_UVRect.yMin)); helper.AddVert(new Vector3(zero.x, zero.w), color, new Vector2(this.m_UVRect.xMin, this.m_UVRect.yMax)); helper.AddVert(new Vector3(zero.z, zero.w), color, new Vector2(this.m_UVRect.xMax, this.m_UVRect.yMax)); helper.AddVert(new Vector3(zero.z, zero.y), color, new Vector2(this.m_UVRect.xMax, this.m_UVRect.yMin)); helper.AddTriangle(0, 1, 2); helper.AddTriangle(2, 3, 0); helper.FillMesh(toFill); } } }
static int get_sharedMesh(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.MeshCollider obj = (UnityEngine.MeshCollider)o; UnityEngine.Mesh ret = obj.sharedMesh; ToLua.Push(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index sharedMesh on a nil value" : e.Message)); } }
static int get_sharedMesh(IntPtr L) { UnityEngine.MeshCollider obj = (UnityEngine.MeshCollider)ToLua.ToObject(L, 1); UnityEngine.Mesh ret = null; try { ret = obj.sharedMesh; } catch (Exception e) { return(LuaDLL.luaL_error(L, obj == null ? "attempt to index sharedMesh on a nil value" : e.Message)); } ToLua.Push(L, ret); return(1); }
static public int GetBlendShapeFrameWeight(IntPtr l) { try { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); var ret = self.GetBlendShapeFrameWeight(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static int get_additionalVertexStreams(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.MeshRenderer obj = (UnityEngine.MeshRenderer)o; UnityEngine.Mesh ret = obj.additionalVertexStreams; ToLua.PushSealed(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index additionalVertexStreams on a nil value")); } }
static int set_sharedMesh(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.MeshCollider obj = (UnityEngine.MeshCollider)o; UnityEngine.Mesh arg0 = (UnityEngine.Mesh)ToLua.CheckUnityObject(L, 2, typeof(UnityEngine.Mesh)); obj.sharedMesh = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index sharedMesh on a nil value" : e.Message)); } }
static int set_additionalVertexStreams(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.MeshRenderer obj = (UnityEngine.MeshRenderer)o; UnityEngine.Mesh arg0 = (UnityEngine.Mesh)ToLua.CheckObject(L, 2, typeof(UnityEngine.Mesh)); obj.additionalVertexStreams = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index additionalVertexStreams on a nil value")); } }
static int set_mesh(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.ParticleSystemRenderer obj = (UnityEngine.ParticleSystemRenderer)o; UnityEngine.Mesh arg0 = (UnityEngine.Mesh)ToLua.CheckObject(L, 2, typeof(UnityEngine.Mesh)); obj.mesh = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index mesh on a nil value")); } }
static int set_sharedMesh(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.SkinnedMeshRenderer obj = (UnityEngine.SkinnedMeshRenderer)o; UnityEngine.Mesh arg0 = (UnityEngine.Mesh)ToLua.CheckObject <UnityEngine.Mesh>(L, 2); obj.sharedMesh = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index sharedMesh on a nil value")); } }
static int get_sharedMesh(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.SkinnedMeshRenderer obj = (UnityEngine.SkinnedMeshRenderer)o; UnityEngine.Mesh ret = obj.sharedMesh; ToLua.PushSealed(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index sharedMesh on a nil value")); } }
static public int CombineMeshes(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (argc == 2) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); self.CombineMeshes(a1); pushValue(l, true); return(1); } else if (argc == 3) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); self.CombineMeshes(a1, a2); pushValue(l, true); return(1); } else if (argc == 4) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); System.Boolean a3; checkType(l, 4, out a3); self.CombineMeshes(a1, a2, a3); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function CombineMeshes to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int GetUVs(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (matchType(l, argc, 2, typeof(int), typeof(List <UnityEngine.Vector4>))) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Collections.Generic.List <UnityEngine.Vector4> a2; checkType(l, 3, out a2); self.GetUVs(a1, a2); pushValue(l, true); return(1); } else if (matchType(l, argc, 2, typeof(int), typeof(List <UnityEngine.Vector3>))) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Collections.Generic.List <UnityEngine.Vector3> a2; checkType(l, 3, out a2); self.GetUVs(a1, a2); pushValue(l, true); return(1); } else if (matchType(l, argc, 2, typeof(int), typeof(List <UnityEngine.Vector2>))) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Collections.Generic.List <UnityEngine.Vector2> a2; checkType(l, 3, out a2); self.GetUVs(a1, a2); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function GetUVs to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int SetIndices(IntPtr l) { try { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32[] a1; checkArray(l, 2, out a1); UnityEngine.MeshTopology a2; checkEnum(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); self.SetIndices(a1, a2, a3); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
static int BakeMesh(IntPtr L) { #if UNITY_EDITOR ToluaProfiler.AddCallRecord("UnityEngine.SkinnedMeshRenderer.BakeMesh"); #endif try { ToLua.CheckArgsCount(L, 2); UnityEngine.SkinnedMeshRenderer obj = (UnityEngine.SkinnedMeshRenderer)ToLua.CheckObject <UnityEngine.SkinnedMeshRenderer>(L, 1); UnityEngine.Mesh arg0 = (UnityEngine.Mesh)ToLua.CheckObject(L, 2, typeof(UnityEngine.Mesh)); obj.BakeMesh(arg0); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int AddBlendShapeFrame(IntPtr L) { try { ToLua.CheckArgsCount(L, 6); UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.CheckObject(L, 1, typeof(UnityEngine.Mesh)); string arg0 = ToLua.CheckString(L, 2); float arg1 = (float)LuaDLL.luaL_checknumber(L, 3); UnityEngine.Vector3[] arg2 = ToLua.CheckObjectArray <UnityEngine.Vector3>(L, 4); UnityEngine.Vector3[] arg3 = ToLua.CheckObjectArray <UnityEngine.Vector3>(L, 5); UnityEngine.Vector3[] arg4 = ToLua.CheckObjectArray <UnityEngine.Vector3>(L, 6); obj.AddBlendShapeFrame(arg0, arg1, arg2, arg3, arg4); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int get_sharedMesh(IntPtr L) { #if UNITY_EDITOR ToluaProfiler.AddCallRecord("UnityEngine.SkinnedMeshRenderer.sharedMesh"); #endif object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.SkinnedMeshRenderer obj = (UnityEngine.SkinnedMeshRenderer)o; UnityEngine.Mesh ret = obj.sharedMesh; ToLua.PushSealed(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index sharedMesh on a nil value")); } }
static int get_additionalVertexStreams(IntPtr L) { #if UNITY_EDITOR ToluaProfiler.AddCallRecord("UnityEngine.MeshRenderer.additionalVertexStreams"); #endif object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.MeshRenderer obj = (UnityEngine.MeshRenderer)o; UnityEngine.Mesh ret = obj.additionalVertexStreams; ToLua.PushSealed(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index additionalVertexStreams on a nil value")); } }
static int set_sharedMesh(IntPtr L) { #if UNITY_EDITOR ToluaProfiler.AddCallRecord("UnityEngine.SkinnedMeshRenderer.sharedMesh"); #endif object o = null; try { o = ToLua.ToObject(L, 1); UnityEngine.SkinnedMeshRenderer obj = (UnityEngine.SkinnedMeshRenderer)o; UnityEngine.Mesh arg0 = (UnityEngine.Mesh)ToLua.CheckObject(L, 2, typeof(UnityEngine.Mesh)); obj.sharedMesh = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index sharedMesh on a nil value")); } }
static int CombineMeshes(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(UnityEngine.CombineInstance[]))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); UnityEngine.CombineInstance[] arg0 = ToLua.CheckObjectArray <UnityEngine.CombineInstance>(L, 2); obj.CombineMeshes(arg0); return(0); } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(UnityEngine.CombineInstance[]), typeof(bool))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); UnityEngine.CombineInstance[] arg0 = ToLua.CheckObjectArray <UnityEngine.CombineInstance>(L, 2); bool arg1 = LuaDLL.lua_toboolean(L, 3); obj.CombineMeshes(arg0, arg1); return(0); } else if (count == 4 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(UnityEngine.CombineInstance[]), typeof(bool), typeof(bool))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); UnityEngine.CombineInstance[] arg0 = ToLua.CheckObjectArray <UnityEngine.CombineInstance>(L, 2); bool arg1 = LuaDLL.lua_toboolean(L, 3); bool arg2 = LuaDLL.lua_toboolean(L, 4); obj.CombineMeshes(arg0, arg1, arg2); return(0); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Mesh.CombineMeshes")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int GetUVs(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(int), typeof(System.Collections.Generic.List <UnityEngine.Vector4>))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.lua_tonumber(L, 2); System.Collections.Generic.List <UnityEngine.Vector4> arg1 = (System.Collections.Generic.List <UnityEngine.Vector4>)ToLua.ToObject(L, 3); obj.GetUVs(arg0, arg1); return(0); } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(int), typeof(System.Collections.Generic.List <UnityEngine.Vector3>))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.lua_tonumber(L, 2); System.Collections.Generic.List <UnityEngine.Vector3> arg1 = (System.Collections.Generic.List <UnityEngine.Vector3>)ToLua.ToObject(L, 3); obj.GetUVs(arg0, arg1); return(0); } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(int), typeof(System.Collections.Generic.List <UnityEngine.Vector2>))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.lua_tonumber(L, 2); System.Collections.Generic.List <UnityEngine.Vector2> arg1 = (System.Collections.Generic.List <UnityEngine.Vector2>)ToLua.ToObject(L, 3); obj.GetUVs(arg0, arg1); return(0); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Mesh.GetUVs")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static public int SetIndices(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (argc == 4) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32[] a1; checkArray(l, 2, out a1); UnityEngine.MeshTopology a2; checkEnum(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); self.SetIndices(a1, a2, a3); pushValue(l, true); return(1); } else if (argc == 5) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.Int32[] a1; checkArray(l, 2, out a1); UnityEngine.MeshTopology a2; checkEnum(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); self.SetIndices(a1, a2, a3, a4); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function SetIndices to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int AddBlendShapeFrame(IntPtr l) { try { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); System.String a1; checkType(l, 2, out a1); System.Single a2; checkType(l, 3, out a2); UnityEngine.Vector3[] a3; checkArray(l, 4, out a3); UnityEngine.Vector3[] a4; checkArray(l, 5, out a4); UnityEngine.Vector3[] a5; checkArray(l, 6, out a5); self.AddBlendShapeFrame(a1, a2, a3, a4, a5); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
static int _CreateUnityEngine_Mesh(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 0) { UnityEngine.Mesh obj = new UnityEngine.Mesh(); ToLua.Push(L, obj); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.Mesh.New")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static public int get_isReadable(IntPtr l) { UnityEngine.Mesh o = (UnityEngine.Mesh)checkSelf(l); pushValue(l, o.isReadable); return(1); }
private BlobAssetReference <Collider> CreateCollider(UnityEngine.Mesh mesh, ColliderType type) { switch (type) { case ColliderType.Sphere: { Bounds bounds = mesh.bounds; return(SphereCollider.Create(bounds.center, math.cmax(bounds.extents))); } case ColliderType.Triangle: { return(PolygonCollider.CreateTriangle(mesh.vertices[0], mesh.vertices[1], mesh.vertices[2])); } case ColliderType.Quad: { // We assume the first 2 triangles of the mesh are a quad with a shared edge // Work out a correct ordering for the triangle int[] orderedIndices = new int[4]; // Find the vertex in first triangle that is not on the shared edge for (int i = 0; i < 3; i++) { if ((mesh.triangles[i] != mesh.triangles[3]) && (mesh.triangles[i] != mesh.triangles[4]) && (mesh.triangles[i] != mesh.triangles[5])) { // Push in order or prev, unique, next orderedIndices[0] = mesh.triangles[(i - 1 + 3) % 3]; orderedIndices[1] = mesh.triangles[i]; orderedIndices[2] = mesh.triangles[(i + 1) % 3]; break; } } // Find the vertex in second triangle that is not on a shared edge for (int i = 3; i < 6; i++) { if ((mesh.triangles[i] != orderedIndices[0]) && (mesh.triangles[i] != orderedIndices[1]) && (mesh.triangles[i] != orderedIndices[2])) { orderedIndices[3] = mesh.triangles[i]; break; } } return(PolygonCollider.CreateQuad( mesh.vertices[orderedIndices[0]], mesh.vertices[orderedIndices[1]], mesh.vertices[orderedIndices[2]], mesh.vertices[orderedIndices[3]])); } case ColliderType.Box: { Bounds bounds = mesh.bounds; return(BoxCollider.Create(bounds.center, quaternion.identity, 2.0f * bounds.extents, 0.0f)); } case ColliderType.Capsule: { Bounds bounds = mesh.bounds; float min = math.cmin(bounds.extents); float max = math.cmax(bounds.extents); int x = math.select(math.select(2, 1, min == bounds.extents.y), 0, min == bounds.extents.x); int z = math.select(math.select(2, 1, max == bounds.extents.y), 0, max == bounds.extents.x); int y = math.select(math.select(2, 1, (1 != x) && (1 != z)), 0, (0 != x) && (0 != z)); float radius = bounds.extents[y]; float3 vertex0 = bounds.center; vertex0[z] = -(max - radius); float3 vertex1 = bounds.center; vertex1[z] = (max - radius); return(CapsuleCollider.Create(vertex0, vertex1, radius)); } case ColliderType.Cylinder: // TODO: need someone to add throw new NotImplementedException(); case ColliderType.Convex: { NativeArray <float3> points = new NativeArray <float3>(mesh.vertices.Length, Allocator.Temp); for (int i = 0; i < mesh.vertices.Length; i++) { points[i] = mesh.vertices[i]; } return(ConvexCollider.Create(points, 0.0f)); } default: throw new System.NotImplementedException(); } }
static public int get_colors(IntPtr l) { UnityEngine.Mesh o = (UnityEngine.Mesh)checkSelf(l); pushValue(l, o.colors); return(1); }
public static void Convert(ModelResourceNode gmdl, string inputPath, string outputPath) { // Create a game object and helper objects to recreate the mesh // from the source file. Get file name without .gmdl.gfxbin // extension. GameObject mainObject = new GameObject((Path.GetFileNameWithoutExtension(inputPath)).Split('.')[0]); GameObject meshObject = new GameObject("Mesh"); meshObject.transform.parent = mainObject.transform; GameObject parts_Base = new GameObject("Parts_Base"); parts_Base.transform.parent = meshObject.transform; foreach (MeshContainer meshContainer in gmdl.MeshContainers) { // I'm pretty sure the Count variable is optimized such that // this won't damage performance, but if the script becomes // slow try storing count in a variable before entering the // loop. foreach (SQEX.Luminous.Renderer.Mesh luminMesh in meshContainer.Meshes) { GameObject gameObject = new GameObject(luminMesh.Name); gameObject.transform.parent = parts_Base.transform; UnityEngine.Mesh mesh = new UnityEngine.Mesh(); UnityEngine.SkinnedMeshRenderer smr = gameObject.AddComponent <SkinnedMeshRenderer>(); List <Vector3> luminVertices = new List <Vector3>(); List <Vector3> normalsList = new List <Vector3>(); Vector3[] normalsArray; List <Vector4> tangentList = new List <Vector4>(); List <int> triangles = new List <int>(); // Read the vertex information from the input file and // convert the list (vertex information) at each position // to an array of doubles List <float> positions = luminMesh.VertexElementArrays["POSITION0"] as List <float>; float[] floatPositions = (from Position in positions select Position).ToArray(); int[] indices = (from index in luminMesh.GmdlGeometry.IdxBuffer select(int) index).ToArray(); // Convert triangles to proper order for unity normals for (var j = 0; j < indices.Length; j += 3) { var a = indices[j]; indices[j] = indices[j + 2]; indices[j + 2] = a; } // Load the vertices into a vector3 list for (uint j = 0; j < luminMesh.VertexCount * 3; j += 3) { luminVertices.Add(new Vector3(floatPositions[j], floatPositions[j + 1], floatPositions[j + 2])); } foreach (int triangle in indices) { triangles.Add(triangle); } // TODO: Figure out why I am passing the mesh to these // functions. It doesn't look like I'm using them. if (luminMesh.VertexElementArrays.ContainsKey("NORMAL0")) { AddLayerNormal(luminMesh.VertexElementArrays["NORMAL0"], ref normalsList, mesh); normalsArray = normalsList.ToArray(); } if (luminMesh.VertexElementArrays.ContainsKey("TANGENT0")) { AddLayerTangent(luminMesh.VertexElementArrays["TANGENT0"], ref tangentList, normalsList.ToArray()); } // Set mesh parts mesh.vertices = luminVertices.ToArray(); mesh.normals = normalsList.ToArray(); mesh.triangles = triangles.ToArray(); mesh.tangents = tangentList.ToArray(); smr.sharedMesh = mesh; // This temp hack causes the script to only write the // first mesh which reduces the amount of time each test // takes. // break; } } }
// Show and process inspector public override void OnInspectorGUI() { Mesh voxelMesh = (Mesh)target; // Flag to enable or disable processing bool process = EditorGUILayout.Toggle("Enabled", voxelMesh.process); if (voxelMesh.process != process) { Undo.RecordObject(voxelMesh, "Processing Change"); voxelMesh.process = process; } // Add title to bar Rect rect = GUILayoutUtility.GetLastRect(); rect.x += EditorGUIUtility.currentViewWidth * 0.5f; rect.y -= rect.height; EditorGUI.LabelField(rect, Information.Title); // Object selection for a mesh to use as a voxel UnityEngine.Mesh mesh = (UnityEngine.Mesh)EditorGUILayout.ObjectField("Voxel Mesh", voxelMesh.mesh, typeof(UnityEngine.Mesh), true); if (voxelMesh.mesh != mesh) { Undo.RecordObject(voxelMesh, "Voxel Mesh Change"); voxelMesh.mesh = mesh; } // Sizing factor for the voxel mesh EditorGUILayout.BeginHorizontal(); float sizeFactor = EditorGUILayout.FloatField("Size Factor", voxelMesh.sizeFactor); if (GUILayout.Button("Reset")) { sizeFactor = 1; } if (voxelMesh.sizeFactor != sizeFactor) { Undo.RecordObject(voxelMesh, "Size Factor Change"); voxelMesh.sizeFactor = sizeFactor; } EditorGUILayout.EndHorizontal(); // Flag to make new containers static EditorGUILayout.BeginHorizontal(); bool staticContainers = EditorGUILayout.Toggle("Static Containers", voxelMesh.staticContainers); if (voxelMesh.staticContainers != staticContainers) { Undo.RecordObject(voxelMesh, "Static Containers Change"); voxelMesh.staticContainers = staticContainers; } //bool skinnedMesh = EditorGUILayout.ToggleLeft("Skinned Mesh", voxelMesh.skinnedMesh); //if (voxelMesh.skinnedMesh != skinnedMesh) //{ // Undo.RecordObject(voxelMesh, "Skinned Mesh Flag Change"); // voxelMesh.skinnedMesh = skinnedMesh; //} EditorGUILayout.EndHorizontal(); // Flag to merge meshes with equal materials EditorGUILayout.BeginHorizontal(); bool mergeMeshes = EditorGUILayout.Toggle("Merge Meshes", voxelMesh.mergeMeshes); if (voxelMesh.mergeMeshes != mergeMeshes) { Undo.RecordObject(voxelMesh, "Meshes Merging Change"); voxelMesh.mergeMeshes = mergeMeshes; } // Flag to merge only meshes with opaque materials EditorGUI.BeginDisabledGroup(!mergeMeshes); bool opaqueOnly = EditorGUILayout.ToggleLeft("Opaque Only", voxelMesh.opaqueOnly); if (voxelMesh.opaqueOnly != opaqueOnly) { Undo.RecordObject(voxelMesh, "Only Opaque Mesh Merging Change"); voxelMesh.opaqueOnly = opaqueOnly; } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); // Elements to fill a texture EditorGUILayout.BeginHorizontal(); bool mainTextureTarget = EditorGUILayout.ToggleLeft("Main Texture", voxelMesh.mainTextureTarget, GUILayout.MaxWidth(128)); if (voxelMesh.mainTextureTarget != mainTextureTarget) { Undo.RecordObject(voxelMesh, "Main Texture Target Flag Change"); voxelMesh.mainTextureTarget = mainTextureTarget; } bool emissiveTextureTarget = EditorGUILayout.ToggleLeft("Emission Texture", voxelMesh.emissiveTextureTarget, GUILayout.MaxWidth(128)); if (voxelMesh.emissiveTextureTarget != emissiveTextureTarget) { Undo.RecordObject(voxelMesh, "Emissive Texture Target Flag Change"); voxelMesh.emissiveTextureTarget = emissiveTextureTarget; } // Flag to transfer material to vertex color bool vertexColors = EditorGUILayout.ToggleLeft("Vertex Colors", voxelMesh.vertexColors, GUILayout.MaxWidth(128)); if (voxelMesh.vertexColors != vertexColors) { Undo.RecordObject(voxelMesh, "Vertex Color Flag Change"); voxelMesh.vertexColors = vertexColors; } EditorGUILayout.EndHorizontal(); //// Object selection for a voxel texture to use for colors //VoxelTexture voxelTexture = (VoxelTexture)EditorGUILayout.ObjectField("Color Texture", voxelMesh.voxelTexture, typeof(VoxelTexture), true); //if (voxelMesh.voxelTexture != voxelTexture) //{ // Undo.RecordObject(voxelMesh, "Color Texture Change"); // voxelMesh.voxelTexture = voxelTexture; //} //if (voxelMesh.voxelTexture != null) //{ // // Object selection of a material to use for texturing // EditorGUILayout.BeginHorizontal(); // EditorGUILayout.LabelField("", GUILayout.MaxWidth(16)); // Material templateMaterial = (Material)EditorGUILayout.ObjectField("Material Template", voxelMesh.textureMaterialTemplate, typeof(Material), true); // if (voxelMesh.textureMaterialTemplate != templateMaterial) // { // Undo.RecordObject(voxelMesh, "Texture Template Material Change"); // voxelMesh.textureMaterialTemplate = templateMaterial; // } // EditorGUILayout.EndHorizontal(); //} //VoxelTexture[] voxelTextures = voxelMesh.GetComponents<VoxelTexture>(); //if (voxelTextures.Length >= 1) //{ // string[] names = new string[voxelTextures.Length + 1]; // int[] indices = new int[voxelTextures.Length + 1]; // int number; // int index = -1; // names[0] = "(none)"; // indices[0] = -1; // for (number = 0; number < voxelTextures.Length; ++number) // { // if (voxelMesh.voxelTexture == voxelTextures[number]) // { // index = number; // } // names[number + 1] = voxelTextures[number].name + " (" + number + ")"; // indices[number + 1] = index; // } // index = EditorGUILayout.IntPopup("Color Texture", index, names, indices); // //if (voxelConverter.bakingOperationMode != bakingOperationMode) // //{ // // Undo.RecordObject(voxelConverter, "Baking Operation Mode Change"); // // voxelConverter.bakingOperationMode = bakingOperationMode; // //} //} // Name of the main target container string targetName = EditorGUILayout.TextField("Target Name", voxelMesh.targetName); if (voxelMesh.targetName != targetName) { Undo.RecordObject(voxelMesh, "Target Object Name Change"); voxelMesh.targetName = targetName; } }
static public int get_tangents(IntPtr l) { UnityEngine.Mesh o = (UnityEngine.Mesh)checkSelf(l); pushValue(l, o.tangents); return(1); }
private static void AddLayerNormal(IList rawNormals, ref List <Vector3> normalsList, UnityEngine.Mesh mesh) { float[] normalsConverted = ConvertToFloatArray(rawNormals); for (int i = 0; i < normalsConverted.Length; i += 4) { normalsList.Add(new Vector3(/*-*/ normalsConverted[i], normalsConverted[i + 1], /*-*/ normalsConverted[i + 2])); } }
protected virtual void CreateMeshPrimitive(MeshPrimitive primitive, string meshName, int meshID, int primitiveIndex) { var meshAttributes = BuildMeshAttributes(primitive, meshID, primitiveIndex); var vertexCount = primitive.Attributes[SemanticProperties.POSITION].Value.Count; UnityEngine.Mesh mesh = new UnityEngine.Mesh { vertices = primitive.Attributes.ContainsKey(SemanticProperties.POSITION) ? meshAttributes[SemanticProperties.POSITION].AccessorContent.AsVertices.ToUnityVector3() : null, normals = primitive.Attributes.ContainsKey(SemanticProperties.NORMAL) ? meshAttributes[SemanticProperties.NORMAL].AccessorContent.AsNormals.ToUnityVector3() : null, uv = primitive.Attributes.ContainsKey(SemanticProperties.TexCoord(0)) ? meshAttributes[SemanticProperties.TexCoord(0)].AccessorContent.AsTexcoords.ToUnityVector2() : null, uv2 = primitive.Attributes.ContainsKey(SemanticProperties.TexCoord(1)) ? meshAttributes[SemanticProperties.TexCoord(1)].AccessorContent.AsTexcoords.ToUnityVector2() : null, uv3 = primitive.Attributes.ContainsKey(SemanticProperties.TexCoord(2)) ? meshAttributes[SemanticProperties.TexCoord(2)].AccessorContent.AsTexcoords.ToUnityVector2() : null, uv4 = primitive.Attributes.ContainsKey(SemanticProperties.TexCoord(3)) ? meshAttributes[SemanticProperties.TexCoord(3)].AccessorContent.AsTexcoords.ToUnityVector2() : null, colors = primitive.Attributes.ContainsKey(SemanticProperties.Color(0)) ? meshAttributes[SemanticProperties.Color(0)].AccessorContent.AsColors.ToUnityColor() : null, triangles = primitive.Indices != null ? meshAttributes[SemanticProperties.INDICES].AccessorContent.AsTriangles : MeshPrimitive.GenerateTriangles(vertexCount), tangents = primitive.Attributes.ContainsKey(SemanticProperties.TANGENT) ? meshAttributes[SemanticProperties.TANGENT].AccessorContent.AsTangents.ToUnityVector4(true) : null }; if (primitive.Attributes.ContainsKey(SemanticProperties.JOINT) && primitive.Attributes.ContainsKey(SemanticProperties.WEIGHT)) { Vector4[] bones = new Vector4[1]; Vector4[] weights = new Vector4[1]; LoadSkinnedMeshAttributes(meshID, primitiveIndex, ref bones, ref weights); if (bones.Length != mesh.vertices.Length || weights.Length != mesh.vertices.Length) { Debug.LogError("Not enough skinning data (bones:" + bones.Length + " weights:" + weights.Length + " verts:" + mesh.vertices.Length + ")"); return; } BoneWeight[] bws = new BoneWeight[mesh.vertices.Length]; int maxBonesIndex = 0; for (int i = 0; i < bws.Length; ++i) { // Unity seems expects the the sum of weights to be 1. float[] normalizedWeights = GLTFUtils.normalizeBoneWeights(weights[i]); bws[i].boneIndex0 = (int)bones[i].x; bws[i].weight0 = normalizedWeights[0]; bws[i].boneIndex1 = (int)bones[i].y; bws[i].weight1 = normalizedWeights[1]; bws[i].boneIndex2 = (int)bones[i].z; bws[i].weight2 = normalizedWeights[2]; bws[i].boneIndex3 = (int)bones[i].w; bws[i].weight3 = normalizedWeights[3]; maxBonesIndex = (int)Mathf.Max(maxBonesIndex, bones[i].x, bones[i].y, bones[i].z, bones[i].w); } mesh.boneWeights = bws; // initialize inverseBindMatrix array with identity matrix in order to output a valid mesh object Matrix4x4[] bindposes = new Matrix4x4[maxBonesIndex + 1]; for (int j = 0; j <= maxBonesIndex; ++j) { bindposes[j] = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one); } mesh.bindposes = bindposes; } if (primitive.Targets != null && primitive.Targets.Count > 0) { for (int b = 0; b < primitive.Targets.Count; ++b) { Vector3[] deltaVertices = new Vector3[primitive.Targets[b]["POSITION"].Value.Count]; Vector3[] deltaNormals = new Vector3[primitive.Targets[b]["POSITION"].Value.Count]; Vector3[] deltaTangents = new Vector3[primitive.Targets[b]["POSITION"].Value.Count]; if (primitive.Targets[b].ContainsKey("POSITION")) { NumericArray num = new NumericArray(); deltaVertices = primitive.Targets[b]["POSITION"].Value.AsVector3Array(ref num, _assetCache.BufferCache[0], false).ToUnityVector3(true); } if (primitive.Targets[b].ContainsKey("NORMAL")) { NumericArray num = new NumericArray(); deltaNormals = primitive.Targets[b]["NORMAL"].Value.AsVector3Array(ref num, _assetCache.BufferCache[0], true).ToUnityVector3(true); } //if (primitive.Targets[b].ContainsKey("TANGENT")) //{ // deltaTangents = primitive.Targets[b]["TANGENT"].Value.AsVector3Array(ref num, _assetCache.BufferCache[0], true).ToUnityVector3(true); //} mesh.AddBlendShapeFrame(GLTFUtils.buildBlendShapeName(meshID, b), 1.0f, deltaVertices, deltaNormals, deltaTangents); } } mesh.RecalculateBounds(); mesh.RecalculateTangents(); mesh = _assetManager.saveMesh(mesh, meshName + "_" + meshID + "_" + primitiveIndex); UnityEngine.Material material = primitive.Material != null && primitive.Material.Id >= 0 ? getMaterial(primitive.Material.Id) : defaultMaterial; _assetManager.addPrimitiveMeshData(meshID, primitiveIndex, mesh, material); }