Hi, all.
I am new in Unity3d, and mayble I’ve missed something but …
I need to import and stl-file into unity3d, so I wrote this code:
using System.IO;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Class adds me an ability to import *.stl files
/// </summary>
// ReSharper disable CheckNamespace
public class StlReader : MonoBehaviour {
// ReSharper restore CheckNamespace
/// <summary>
/// The number of the maximum vertexes in model
/// </summary>
protected static int MaxVertexCount = 64500;
/// <summary>
/// Contains the whole model triangles count
/// </summary>
protected uint TrianglesCount { get; set; }
/// <summary>
/// List of all imported meshes
/// </summary>
protected List<Mesh> Meshes = new List<Mesh>();
/// <summary>
/// Reads the file and creates meshes within 65 000 of triangles
/// </summary>
/// <param name="fileName">name of the file</param>
/// <returns>List of meshes</returns>
public List<Mesh> Read(string fileName) {
var bytes = System.IO.File.ReadAllBytes(fileName);
var reader = new BinaryReader(new MemoryStream(bytes));
reader.ReadBytes(80);
var trianglesCount = reader.ReadUInt32();
TrianglesCount = trianglesCount;
Debug.Log(trianglesCount);
var vertices = new List<Vector3>();
var triangles = new List<int>();
var triangle = 0;
var items = new Dictionary<string, Vector3>();
for (var i = 0; i < trianglesCount; i++){
// the normal
reader.ReadSingle();
reader.ReadSingle();
reader.ReadSingle();
var vertex1 = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
var vertex2 = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
var vertex3 = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
vertices.Add(vertex1);
vertices.Add(vertex2);
vertices.Add(vertex3);
triangles.Add(triangle++);
triangles.Add(triangle++);
triangles.Add(triangle++);
reader.ReadUInt16(); // byte count
if (vertices.Count <= MaxVertexCount - 1){
continue;
}
AddMesh(vertices, triangles);
vertices.Clear();
triangles.Clear();
items.Clear();
triangle = 0;
}
if (vertices.Count > 0) {
AddMesh(vertices, triangles);
}
return Meshes;
}
/// <summary>
/// Adds new mesh to the list
/// </summary>
/// <param name="vertices"></param>
/// <param name="triangles"></param>
protected void AddMesh(List<Vector3> vertices, List<int> triangles) {
var mesh = new Mesh {
vertices = vertices.ToArray(),
triangles = triangles.ToArray()
};
mesh.RecalculateNormals();
mesh.Optimize();
Meshes.Add(mesh);
}
}
all is quite simple except the quality of the model ![]()
Take a look:
http://www.freeimagehosting.net/8jwiu
As you see, there is no smooth :((
I read about the vertex normals, but I cannot make them work, because size of normals array should be the same as vertex array.
Maybe you have some ideas, how I can make model smooth?
Any help will be appreciated, thanks!