public void Export(string filePath) { PalletProperties palletProperties = _palletSolution.Analysis.PalletProperties; COLLADA model = new COLLADA(); // asset model.asset = new asset() { created = DateTime.Now, modified = DateTime.Now }; model.asset.keywords = "StackBuilder Pallet Case"; model.asset.title = _palletSolution.Title; model.asset.unit = new assetUnit() { name = "millimeters", meter = 0.001 }; model.asset.up_axis = UpAxisType.Z_UP; library_images images = new library_images(); library_materials materials = new library_materials(); library_effects effects = new library_effects(); library_geometries geometries = new library_geometries(); library_nodes nodes = new library_nodes(); library_cameras cameras = new library_cameras(); library_animations animations = new library_animations(); library_visual_scenes scenes = new library_visual_scenes(); COLLADAScene colladaScene = new COLLADAScene(); model.Items = new Object[] { images, materials, effects, geometries, nodes, cameras, animations, scenes }; model.scene = colladaScene; // colors and materials List<effect> listEffects = new List<effect>(); List<material> listMaterials = new List<material>(); List<image> listImages = new List<image>(); // effects effect effectPallet; material materialPallet; CreateMaterial(palletProperties.Color, null, null, "Pallet", out effectPallet, out materialPallet); listEffects.Add(effectPallet); listMaterials.Add(materialPallet); Box box = new Box(0, _palletSolution.Analysis.BProperties); // build list of effects / materials / images uint faceIndex = 0; foreach (Face face in box.Faces) { // build texture image if any string textureName = null; if (face.HasBitmap) { textureName = string.Format("textureFace_{0}", faceIndex); string texturePath = System.IO.Path.Combine( System.IO.Path.GetDirectoryName(filePath) , textureName + ".jpg"); double dimX = 0.0, dimY = 0.0; switch (faceIndex) { case 0: dimX = box.Width; dimY = box.Height; break; case 1: dimX = box.Width; dimY = box.Height; break; case 2: dimX = box.Length; dimY = box.Height; break; case 3: dimX = box.Length; dimY = box.Height; break; case 4: dimX = box.Length; dimY = box.Width; break; case 5: dimX = box.Length; dimY = box.Width; break; default: break; } face.ExtractFaceBitmap(dimX, dimY, _bmpWidth, texturePath); // create image listImages.Add( new image() { id = textureName + ".jpg", name = textureName + ".jpg", Item = @".\" + textureName + @".jpg" } ); } material materialCase; effect effectCase; CreateMaterial(face.ColorFill, textureName, "0", string.Format("Case{0}", faceIndex), out effectCase, out materialCase); listEffects.Add(effectCase); listMaterials.Add(materialCase); ++faceIndex; } // add to image list images.image = listImages.ToArray(); // case lines material effect effectCaseLines; material materialCaseLines; CreateMaterial(Color.Black, null, null, "CaseLines", out effectCaseLines, out materialCaseLines); listEffects.Add(effectCaseLines); listMaterials.Add(materialCaseLines); effects.effect = listEffects.ToArray(); materials.material = listMaterials.ToArray(); // geometries geometry geomPallet = new geometry() { id = "palletGeometry", name = "palletGeometry" }; geometry geomCase = new geometry() { id = "caseGeometry", name = "caseGeometry" }; geometries.geometry = new geometry[] { geomPallet, geomCase }; // pallet mesh meshPallet = CreatePalletMesh(palletProperties); geomPallet.Item = meshPallet; // case mesh meshCase = CreateCaseMesh(_palletSolution.Analysis.BProperties as BoxProperties); geomCase.Item = meshCase; // library_animations animation animationMain = new animation() { id = "animationMain_ID", name = "animationMain" }; animations.animation = new animation[] { animationMain }; List<object> listAnimationSource = new List<object>(); // library_visual_scenes visual_scene mainScene = new visual_scene() { id = "MainScene", name = "MainScene" }; scenes.visual_scene = new visual_scene[] { mainScene }; List<node> sceneNodes = new List<node>(); sceneNodes.Add(new node() { id = "PalletNode", name = "PalletNode", instance_geometry = new instance_geometry[] { new instance_geometry() { url = "#palletGeometry", bind_material = new bind_material() { technique_common = new instance_material[] { new instance_material() { symbol="materialPallet", target=string.Format("#{0}", materialPallet.id) } } } } } }); uint caseIndex = 0; foreach (ILayer layer in _palletSolution) { BoxLayer bLayer = layer as BoxLayer; if (null == bLayer) continue; foreach (BoxPosition bp in bLayer) { Vector3D translation = bp.Position; Vector3D rotations = bp.Transformation.Rotations; node caseNode = new node() { id = string.Format("CaseNode_{0}_ID", caseIndex), name = string.Format("CaseNode_{0}", caseIndex), ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.translate, ItemsChoiceType2.rotate, ItemsChoiceType2.rotate, ItemsChoiceType2.rotate }, Items = new object[] { new TargetableFloat3() { Values = new double[] { translation.X, translation.Y, translation.Z }, sid = "t", }, new rotate() { Values = new double[] { 1.0, 0.0, 0.0, rotations.X }, sid = "rx" }, new rotate() { Values = new double[] { 0.0, 1.0, 0.0, rotations.Y }, sid = "ry" }, new rotate() { Values = new double[] { 0.0, 0.0, 1.0, rotations.Z }, sid = "rz" } }, instance_geometry = new instance_geometry[] { new instance_geometry() { url="#caseGeometry", bind_material = new bind_material() { technique_common = new instance_material[] { new instance_material() { symbol="materialCase0", target="#material_Case0_ID" }, new instance_material() { symbol="materialCase1", target="#material_Case1_ID" }, new instance_material() { symbol="materialCase2", target="#material_Case2_ID" }, new instance_material() { symbol="materialCase3", target="#material_Case3_ID" }, new instance_material() { symbol="materialCase4", target="#material_Case4_ID" }, new instance_material() { symbol="materialCase5", target="#material_Case5_ID" }, new instance_material() { symbol="materialCaseLines", target="#material_CaseLines_ID"} } } } } }; sceneNodes.Add(caseNode); // animations CreateAnimation(caseIndex, (uint)_palletSolution.CaseCount, listAnimationSource, bp); // increment case index ++caseIndex; } } // add nodes mainScene.node = sceneNodes.ToArray(); animationMain.Items = listAnimationSource.ToArray(); // library_cameras camera cameraCamera = new camera() { id = "Camera-Camera", name = "Camera-Camera" }; cameraOpticsTechnique_commonPerspective cameraPerspective = new cameraOpticsTechnique_commonPerspective() { znear = new TargetableFloat() { sid = "znear", Value = 1.0 }, zfar = new TargetableFloat() { sid = "zfar", Value = 10000.0 } }; cameraCamera.optics = new cameraOptics() { technique_common = new cameraOpticsTechnique_common() { Item = cameraPerspective } }; cameras.camera = new camera[] { cameraCamera }; // colladaScene colladaScene.instance_visual_scene = new InstanceWithExtra() { url = "#MainScene" }; model.Save(filePath); model.Save(System.IO.Path.ChangeExtension(filePath, "xml")); }
static ColladaGeometry GetGeometry(CL.UpAxisType up, CL.geometry geo, CL.library_materials matlib, CL.library_effects fxlib) { var conv = new ColladaGeometry() { FVF = D3DFVF.XYZ }; conv.Name = string.IsNullOrEmpty(geo.name) ? geo.id : geo.name; var msh = geo.Item as CL.mesh; if (msh == null) { return(null); } List <VertexPositionNormalDiffuseTextureTwo> vertices = new List <VertexPositionNormalDiffuseTextureTwo>(); List <int> hashes = new List <int>(); List <ushort> indices = new List <ushort>(); List <ColladaDrawcall> drawcalls = new List <ColladaDrawcall>(); Dictionary <string, GeometrySource> sources = new Dictionary <string, GeometrySource>(); Dictionary <string, float[]> arrays = new Dictionary <string, float[]>(); Dictionary <string, GeometrySource> verticesRefs = new Dictionary <string, GeometrySource>(); int placeHolderIdx = 0; //Get arrays foreach (var acc in msh.source) { var arr = acc.Item as CL.float_array; arrays.Add(arr.id, FloatArray(arr.Text)); } //Accessors foreach (var acc in msh.source) { sources.Add(acc.id, new GeometrySource(acc, arrays)); } //Process geometry foreach (var item in msh.Items) { if (!(item is CL.triangles || item is CL.polylist || item is CL.polygons)) { FLLog.Warning("Collada", "Ignoring " + item.GetType().Name + " element."); } } int totalTriangles = 0; foreach (var item in msh.Items.Where(x => x is CL.triangles || x is CL.polylist || x is CL.polygons)) { if (item is CL.triangles) { totalTriangles += (int)((CL.triangles)item).count; } else if (item is CL.polylist plist) { totalTriangles += (int)plist.count; } else { totalTriangles += (int)((CL.polygons)item).count; } } if (totalTriangles > 21845) { throw new Exception(string.Format( "Overflow!\nCollada geometry {0} has {1} triangles\nVMeshData has limit of 21845", string.IsNullOrEmpty(geo.name) ? geo.id : geo.name, totalTriangles)); } foreach (var item in msh.Items.Where(x => x is CL.triangles || x is CL.polylist || x is CL.polygons)) { CL.InputLocalOffset[] inputs; int[] pRefs; int indexCount; string materialRef; ColladaMaterial material; if (item is CL.triangles) { var triangles = (CL.triangles)item; indexCount = (int)(triangles.count * 3); pRefs = IntArray(triangles.p); inputs = triangles.input; materialRef = triangles.material; } else if (item is CL.polygons polygons) { indexCount = (int)(polygons.count * 3); int j = 0; pRefs = new int[indexCount]; foreach (var arr in polygons.Items) { if (!(arr is string)) { throw new Exception("Polygons: ph element unsupported"); } var ints = IntArray((string)arr); if (ints.Length != 3) { throw new Exception("Polygons: non-triangle geometry not supported"); } pRefs[j] = ints[0]; pRefs[j + 1] = ints[1]; pRefs[j + 2] = ints[2]; j += 3; } inputs = polygons.input; materialRef = polygons.material; } else { var plist = (CL.polylist)item; pRefs = IntArray(plist.p); foreach (var c in IntArray(plist.vcount)) { if (c != 3) { throw new Exception("Polylist: non-triangle geometry"); } } materialRef = plist.material; inputs = plist.input; indexCount = (int)(plist.count * 3); } if (indexCount == 0) { continue; //Skip empty } material = ParseMaterial(materialRef, matlib, fxlib); int pStride = 0; foreach (var input in inputs) { pStride = Math.Max((int)input.offset, pStride); } pStride++; GeometrySource sourceXYZ = null; int offXYZ = int.MinValue; GeometrySource sourceNORMAL = null; int offNORMAL = int.MinValue; GeometrySource sourceCOLOR = null; int offCOLOR = int.MinValue; GeometrySource sourceUV1 = null; int offUV1 = int.MinValue; GeometrySource sourceUV2 = null; int offUV2 = int.MinValue; int texCount = 0; int startIdx = indices.Count; foreach (var input in inputs) { switch (input.semantic) { case SEM_VERTEX: if (CheckURI(input.source) != msh.vertices.id) { throw new Exception("VERTEX doesn't match mesh vertices"); } foreach (var ip2 in msh.vertices.input) { switch (ip2.semantic) { case SEM_POSITION: offXYZ = (int)input.offset; sourceXYZ = sources[CheckURI(ip2.source)]; break; case SEM_NORMAL: offNORMAL = (int)input.offset; sourceNORMAL = sources[CheckURI(ip2.source)]; conv.FVF |= D3DFVF.NORMAL; break; case SEM_COLOR: offCOLOR = (int)input.offset; sourceCOLOR = sources[CheckURI(ip2.source)]; conv.FVF |= D3DFVF.DIFFUSE; break; case SEM_TEXCOORD: if (texCount == 2) { throw new Exception("Too many texcoords!"); } if (texCount == 1) { offUV2 = (int)input.offset; sourceUV2 = sources[CheckURI(ip2.source)]; conv.FVF &= ~D3DFVF.TEX1; conv.FVF |= D3DFVF.TEX2; } else { offUV1 = (int)input.offset; sourceUV1 = sources[CheckURI(ip2.source)]; if ((conv.FVF & D3DFVF.TEX2) != D3DFVF.TEX2) { conv.FVF |= D3DFVF.TEX1; } } texCount++; break; } } break; case SEM_POSITION: offXYZ = (int)input.offset; sourceXYZ = sources[CheckURI(input.source)]; break; case SEM_NORMAL: offNORMAL = (int)input.offset; sourceNORMAL = sources[CheckURI(input.source)]; conv.FVF |= D3DFVF.NORMAL; break; case SEM_COLOR: offCOLOR = (int)input.offset; sourceCOLOR = sources[CheckURI(input.source)]; conv.FVF |= D3DFVF.DIFFUSE; break; case SEM_TEXCOORD: if (texCount == 2) { throw new Exception("Too many texcoords!"); } if (texCount == 1) { offUV2 = (int)input.offset; sourceUV2 = sources[CheckURI(input.source)]; conv.FVF &= ~D3DFVF.TEX1; conv.FVF |= D3DFVF.TEX2; } else { offUV1 = (int)input.offset; sourceUV1 = sources[CheckURI(input.source)]; if ((conv.FVF & D3DFVF.TEX2) != D3DFVF.TEX2) { conv.FVF |= D3DFVF.TEX1; } } texCount++; break; } } int vertexOffset = vertices.Count; for (int i = 0; i < indexCount; i++) { int idx = i * pStride; var vert = new VertexPositionNormalDiffuseTextureTwo( VecAxis(up, sourceXYZ.GetXYZ(pRefs[idx + offXYZ])), offNORMAL == int.MinValue ? Vector3.Zero : VecAxis(up, sourceNORMAL.GetXYZ(pRefs[idx + offNORMAL])), offCOLOR == int.MinValue ? (uint)Color4.White.ToRgba() : (uint)sourceCOLOR.GetColor(pRefs[idx + offCOLOR]).ToRgba(), offUV1 == int.MinValue ? Vector2.Zero : sourceUV1.GetUV(pRefs[idx + offUV1]), offUV2 == int.MinValue ? Vector2.Zero : sourceUV2.GetUV(pRefs[idx + offUV2]) ); var hash = HashVert(ref vert); var vertIdx = FindDuplicate(hashes, vertices, vertexOffset, ref vert, hash); if (indices.Count >= ushort.MaxValue) { throw new Exception("Too many indices"); } if (vertIdx == -1) { if (vertices.Count + 1 >= ushort.MaxValue) { throw new Exception("Too many vertices"); } indices.Add((ushort)(vertices.Count - vertexOffset)); vertices.Add(vert); hashes.Add(hash); } else { indices.Add((ushort)(vertIdx - vertexOffset)); } } drawcalls.Add(new ColladaDrawcall() { StartIndex = startIdx, StartVertex = vertexOffset, EndVertex = vertices.Count - 1, TriCount = (indices.Count - startIdx) / 3, Material = material }); } conv.Indices = indices.ToArray(); conv.Vertices = vertices.ToArray(); conv.Drawcalls = drawcalls.ToArray(); conv.CalculateDimensions(); return(conv); }
static ColladaMaterial ParseMaterial(string name, CL.library_materials matlib, CL.library_effects fxlib) { if (matlib == null) { return new ColladaMaterial() { Dc = Color4.Red, Name = name } } ; var src = matlib.material.FirstOrDefault(mat => mat.id.Equals(name, StringComparison.InvariantCulture)); if (src == null) { return new ColladaMaterial() { Dc = Color4.Red, Name = name } } ; var output = new ColladaMaterial() { Dc = Color4.Red }; output.Name = string.IsNullOrWhiteSpace(src.name) ? name : src.name; if (src.instance_effect == null) { return(output); } if (fxlib == null) { return(output); } var fx = fxlib.effect.FirstOrDefault(fx => fx.id.Equals(CheckURI(src.instance_effect.url), StringComparison.InvariantCulture)); if (fx != null) { var profile = fx.Items.FirstOfType <CL.effectFx_profile_abstractProfile_COMMON>(); if (profile == null) { return(output); } if (profile.technique == null) { return(output); } switch (profile.technique.Item) { case CL.effectFx_profile_abstractProfile_COMMONTechniquePhong phong: SetDc(output, phong.diffuse); break; case CL.effectFx_profile_abstractProfile_COMMONTechniqueBlinn blinn: SetDc(output, blinn.diffuse); break; case CL.effectFx_profile_abstractProfile_COMMONTechniqueConstant constant: output.Dc = Color4.White; break; case CL.effectFx_profile_abstractProfile_COMMONTechniqueLambert lambert: SetDc(output, lambert.diffuse); break; } } return(output); }
static ColladaObject ProcessNode(CL.UpAxisType up, CL.library_geometries geom, CL.node n, CL.library_materials matlib, CL.library_effects fxlib) { var obj = new ColladaObject(); obj.Name = n.name; obj.ID = n.id; if (n.instance_geometry != null && n.instance_geometry.Length > 0) { //Geometry object if (n.instance_geometry.Length != 1) { throw new Exception("How to handle multiple geometries/node?"); } var uri = CheckURI(n.instance_geometry[0].url); var g = geom.geometry.Where((x) => x.id == uri).First(); if (g.Item is CL.mesh) { obj.Geometry = GetGeometry(up, g, matlib, fxlib); } else if (g.Item is CL.spline) { obj.Spline = GetSpline(up, g); } } if (n.Items.OfType <CL.matrix>().Any()) { var tr = n.Items.OfType <CL.matrix>().First(); obj.Transform = GetMatrix(up, tr.Text); } else { Matrix4x4 mat = Matrix4x4.Identity; foreach (var item in n.Items) { if (item is CL.TargetableFloat3) { //var float3 = } } obj.Transform = mat; } if (n.node1 != null && n.node1.Length > 0) { foreach (var node in n.node1) { obj.Children.Add(ProcessNode(up, geom, node, matlib, fxlib)); } } return(obj); }
public override ModelBase LoadModel(Vector3 scale) { foreach (var item in m_COLLADAModel.Items) { if (item.GetType().Equals(typeof(library_images))) this.library_images = item as library_images; if (item.GetType().Equals(typeof(library_effects))) this.library_effects = item as library_effects; if (item.GetType().Equals(typeof(library_materials))) this.library_materials = item as library_materials; if (item.GetType().Equals(typeof(library_geometries))) this.library_geometries = item as library_geometries; if (item.GetType().Equals(typeof(library_controllers))) this.library_controllers = item as library_controllers; if (item.GetType().Equals(typeof(library_visual_scenes))) this.library_visual_scenes = item as library_visual_scenes; if (item.GetType().Equals(typeof(library_animations))) this.library_animations = item as library_animations; } ReadMaterials(); ReadVisualScenes(); ReadAnimations(); m_Model.ScaleModel(scale); m_Model.ScaleAnimations(scale); return m_Model; }
public static void ExportCollada(CmpFile cmp, ResourceManager resources, string output) { //Build tree InputModel rootModel = null; List <InputModel> parentModels = new List <InputModel>(); foreach (var p in cmp.Parts) { if (p.Construct == null) { rootModel = new InputModel() { Transform = Matrix4x4.Identity, Model = p.Model, Con = "Root" }; break; } } parentModels.Add(rootModel); var q = new Queue <Part>(cmp.Parts); int infiniteDetect = 0; while (q.Count > 0) { var part = q.Dequeue(); if (part.Construct == null) { continue; } bool enqueue = true; foreach (var mdl in parentModels) { if (part.Construct.ParentName == mdl.Con) { var child = new InputModel() { Transform = part.Construct.Rotation * Matrix4x4.CreateTranslation(part.Construct.Origin), Model = part.Model, Con = part.Construct.ChildName }; mdl.Children.Add(child); parentModels.Add(child); enqueue = false; break; } } if (enqueue) { q.Enqueue(part); } infiniteDetect++; if (infiniteDetect > 200000000) { throw new Exception("Infinite cmp loop detected"); } } //Build collada var dae = NewCollada(); var efx = new CL.library_effects(); var mats = new CL.library_materials(); var geos = new CL.library_geometries(); var scenes = new CL.library_visual_scenes(); var vscene = new CL.visual_scene(); vscene.name = vscene.id = "main-scene"; scenes.visual_scene = new CL.visual_scene[] { vscene }; dae.scene = new CL.COLLADAScene(); dae.scene.instance_visual_scene = new CL.InstanceWithExtra() { url = "#main-scene" }; var glist = new List <CL.geometry>(); var mlist = new List <string>(); var matlist = new List <ExportMaterial>(); BuildModel(resources, rootModel, glist, mlist, matlist); geos.geometry = glist.ToArray(); mats.material = mlist.Select((x) => new CL.material() { name = x, id = x + "-material", instance_effect = new CL.instance_effect() { url = "#" + x + "-effect" } }).ToArray(); efx.effect = matlist.Select((x) => new CL.effect() { id = x.Name + "-effect", Items = new[] { new CL.effectFx_profile_abstractProfile_COMMON() { technique = new CL.effectFx_profile_abstractProfile_COMMONTechnique() { id = "common", Item = new CL.effectFx_profile_abstractProfile_COMMONTechniquePhong() { ambient = ColladaColor("ambient", Color4.Black), emission = ColladaColor("emmision", Color4.Black), diffuse = ColladaColor("diffuse", x.Dc), specular = ColladaColor("specular", new Color4(0.25f, 0.25f, 0.25f, 1f)), shininess = ColladaFloat("shininess", 50), index_of_refraction = ColladaFloat("index_of_refraction", 1) } } } } }).ToArray(); var rootNodes = new List <CL.node>(); BuildNodes(rootModel, rootNodes); vscene.node = rootNodes.ToArray(); dae.Items = new object[] { efx, mats, geos, scenes }; using (var stream = File.Create(output)) ColladaSupport.XML.Serialize(stream, dae); }
public static void ExportCollada(ModelFile mdl, ResourceManager resources, string output) { var dae = NewCollada(); var mats = new CL.library_materials(); var efx = new CL.library_effects(); var geos = new CL.library_geometries(); var scenes = new CL.library_visual_scenes(); var vscene = new CL.visual_scene(); vscene.name = vscene.id = "main-scene"; scenes.visual_scene = new CL.visual_scene[] { vscene }; dae.scene = new CL.COLLADAScene(); dae.scene.instance_visual_scene = new CL.InstanceWithExtra() { url = "#main-scene" }; var exported = ProcessModel(mdl, resources); geos.geometry = exported.Geometries.ToArray(); mats.material = exported.Materials.Select((x) => new CL.material() { name = x.Name, id = x.Name + "-material", instance_effect = new CL.instance_effect() { url = "#" + x.Name + "-effect" } }).ToArray(); efx.effect = exported.Materials.Select((x) => new CL.effect() { id = x.Name + "-effect", Items = new[] { new CL.effectFx_profile_abstractProfile_COMMON() { technique = new CL.effectFx_profile_abstractProfile_COMMONTechnique() { id = "common", Item = new CL.effectFx_profile_abstractProfile_COMMONTechniquePhong() { ambient = ColladaColor("ambient", Color4.Black), emission = ColladaColor("emmision", Color4.Black), diffuse = ColladaColor("diffuse", x.Dc), specular = ColladaColor("specular", new Color4(0.25f, 0.25f, 0.25f, 1f)), shininess = ColladaFloat("shininess", 50), index_of_refraction = ColladaFloat("index_of_refraction", 1) } } } } }).ToArray(); var nodes = new List <CL.node>(); for (int i = 0; i < exported.Geometries.Count; i++) { nodes.Add(exported.GetNode(i, Matrix4x4.Identity, mdl.Path)); } vscene.node = nodes.ToArray(); dae.Items = new object[] { efx, mats, geos, scenes }; using (var stream = File.Create(output)) ColladaSupport.XML.Serialize(stream, dae); }