/// <summary> /// 递归创建装配树 /// </summary> /// <param name="component"></param> /// <param name="swComponet"></param> private static void CreateTree(Component2 component, ref SWComponent swComponent) { if (component == null) { return; } /////////复制组件相关信息/////////// //名称 swComponent.Name = component.Name2; //是否根组件 swComponent.IsRoot = component.IsRoot(); //提取配合,存放在RootComponent节点 //if (swComponent.IsRoot) { swComponent.Mates = GetSWMatesOfRootComponent(component); //} //包围盒 double[] box = null; try { box = component.GetBox(false, false); } catch (Exception e) { //发生异常,说明该组件(根组件)没有包围盒 box = null; } if (box == null) { swComponent.BoundingBox = CreateSWBoundingBox(box); } else { swComponent.BoundingBox = new SWBoundingBox(); } //提取Body object bodyInfo; object[] bodies = component.GetBodies3((int)swBodyType_e.swSolidBody, out bodyInfo); if (bodies != null) { foreach (object objBody in bodies) { swComponent.Bodies.Add(CreateSWBody((Body2)objBody)); } } //继续遍历 object[] subComponents = component.GetChildren(); if (subComponents != null) { foreach (object obj in subComponents) { SWComponent newComponent = new SWComponent(); CreateTree((Component2)obj, ref newComponent); swComponent.SubComponents.Add(newComponent); } } }
public static bool hitMainBodyBefore(double[] rayOrigin, double[] rayDirection, double[] hitPointToCompareTo) { List <IBody2> bodies = new List <IBody2>(); object vBodyInfo; object[] componentBodies = (object[])mainBody.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); for (int i = 0; i < componentBodies.Length; i++) { IBody2 tempBody = ((Body2)componentBodies[i]).ICopy(); tempBody.ApplyTransform(mainBody.Transform2); bodies.Add(tempBody); } int numIntersectionsFound = (int)swDoc.RayIntersections((object)bodies.ToArray(), (object)rayOrigin, (object)rayDirection, (int)(swRayPtsOpts_e.swRayPtsOptsTOPOLS | swRayPtsOpts_e.swRayPtsOptsNORMALS | swRayPtsOpts_e.swRayPtsOptsENTRY_EXIT), (double).0000001, (double).0000001); double[] horrifyingReturn = (double[])swDoc.GetRayIntersectionsPoints(); if (numIntersectionsFound == 0) { return(false); } int lengthOfOneReturn = 9; for (int i = 0; i < numIntersectionsFound; i++) { byte intersectionType = (byte)horrifyingReturn[i * lengthOfOneReturn + 2]; if ((intersectionType & (byte)swRayPtsResults_e.swRayPtsResultsENTER) == 0) { // we need it to be just entry rays continue; } double x = horrifyingReturn[i * lengthOfOneReturn + 3]; double y = horrifyingReturn[i * lengthOfOneReturn + 4]; double z = horrifyingReturn[i * lengthOfOneReturn + 5]; if (distanceAlongRay(rayOrigin, new double[] { x, y, z }) < distanceAlongRay(rayOrigin, hitPointToCompareTo)) { return(true); } } return(false); }
public static bool isBody(Component2 swComponent) { object bodiesInfo = null; swComponent.GetBodies3((int)swBodyType_e.swSolidBody, out bodiesInfo); return(bodiesInfo != null && ((int[])bodiesInfo).Length > 0); }
public static double[] whereRayHitsComponent(Component2 component, MathPoint rayOrigin, MathVector rayDirection) { List <IBody2> bodies = new List <IBody2>(); object vBodyInfo; object[] componentBodies = (object[])component.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); for (int i = 0; i < componentBodies.Length; i++) { IBody2 tempBody = ((Body2)componentBodies[i]).ICopy(); tempBody.ApplyTransform(component.Transform2); bodies.Add(tempBody); } int numIntersectionsFound = (int)swDoc.RayIntersections((object)bodies.ToArray(), (object)rayOrigin.ArrayData, (object)rayDirection.ArrayData, (int)(swRayPtsOpts_e.swRayPtsOptsTOPOLS | swRayPtsOpts_e.swRayPtsOptsNORMALS), (double).0000001, (double).0000001); if (numIntersectionsFound == 0) { return(null); } double[] horrifyingReturn = (double[])swDoc.GetRayIntersectionsPoints(); int lengthOfOneReturn = 9; for (int i = 0; i < numIntersectionsFound; i++) { double x = horrifyingReturn[i * lengthOfOneReturn + 3]; double y = horrifyingReturn[i * lengthOfOneReturn + 4]; double z = horrifyingReturn[i * lengthOfOneReturn + 5]; double[] hitPoint = new double[] { x, y, z }; if (!hitMainBodyBefore(rayOrigin.ArrayData, rayDirection.ArrayData, hitPoint)) { return(hitPoint); } } return(null); }
/// Convert a SolidWorks component to Wavefront OBJ mesh /// public static void Convert(Component2 swComp, ref string asciitext, bool saveUV, ref UserProgressBar swProgress) { StringBuilder textbuilder = new StringBuilder(); Body2 swBody = default(Body2); object[] vBodies = null; object[] vBodiesSolid = null; object[] vBodiesSheet = null; object vBodyInfo; int[] BodiesInfo = null; int j = 0; ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc(); vBodiesSolid = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); vBodiesSheet = (object[])swComp.GetBodies3((int)swBodyType_e.swSheetBody, out vBodyInfo); BodiesInfo = (int[])vBodyInfo; if (vBodiesSolid != null && vBodiesSheet == null) { vBodies = vBodiesSolid; } if (vBodiesSolid == null && vBodiesSheet != null) { vBodies = vBodiesSheet; } if (vBodiesSolid != null && vBodiesSheet != null) { vBodies = vBodiesSheet.Concat(vBodiesSolid).ToArray(); } // vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); if (vBodies != null) { int iNumBodies = vBodies.Length; int iNumSolidBodies = 0; int iNumSheetBodies = 0; int iNumTesselatedBodies = 0; if (iNumBodies > 0) { asciitext += "# Wavefront .OBJ file for tesselated shape: " + swComp.Name2 + " path: " + swModel.GetPathName() + "\n\n"; } int group_vstride = 0; int group_nstride = 0; // Loop through bodies for (j = 0; j <= vBodies.Length - 1; j++) { swBody = (Body2)vBodies[j]; int nBodyType = (int)swBody.GetType(); if (nBodyType == (int)swBodyType_e.swSheetBody) { iNumSheetBodies++; } if (nBodyType == (int)swBodyType_e.swSolidBody) { iNumSolidBodies++; } if ((nBodyType == (int)swBodyType_e.swSheetBody || nBodyType == (int)swBodyType_e.swSolidBody) && !swBody.Name.StartsWith("COLL.") && swBody.Visible) { iNumTesselatedBodies++; CultureInfo bz = new CultureInfo("en-BZ"); //asciitext += "g body_" + iNumTesselatedBodies + "\n"; textbuilder.Append("g body_" + iNumTesselatedBodies + "\n"); Face2 swFace = null; Tessellation swTessellation = null; bool bResult = false; // Pass in null so the whole body will be tessellated swTessellation = (Tessellation)swBody.GetTessellation(null); // Set up the Tessellation object swTessellation.NeedFaceFacetMap = true; swTessellation.NeedVertexParams = true; swTessellation.NeedVertexNormal = true; swTessellation.ImprovedQuality = true; // How to handle matches across common edges swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology; // Do it if (swProgress != null) { swProgress.UpdateTitle("Exporting (tesselate process) ..."); } bResult = swTessellation.Tessellate(); // Get the number of vertices and facets //System.Windows.Forms.MessageBox.Show("Body n." + j + " vert.num=" + swTessellation.GetVertexCount()); //Debug.Print("Number of vertices: " + swTessellation.GetVertexCount()); //Debug.Print("Number of facets: " + swTessellation.GetFacetCount()); // Now get the facet data per face int[] aFacetIds; int iNumFacetIds; int[] aFinIds; int[] aVertexIds; double[] aNormal; double[] aVertexCoords1; double[] aVertexCoords2; double[] aVertexParams; int numv = swTessellation.GetVertexCount(); // Write all vertexes string mline; for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th vertex in .obj) ..."); } aVertexCoords1 = (double[])swTessellation.GetVertexPoint(iv); mline = "v " + (aVertexCoords1[0] * ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[1] * ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[2] * ChScale.L).ToString("f6", bz) + "\n"; textbuilder.Append(mline); } // Write all normals for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); } aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + aNormal[0].ToString("f3", bz) + " " + aNormal[1].ToString("f3", bz) + " " + aNormal[2].ToString("f3", bz) + "\n"; textbuilder.Append(mline); } if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles { for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); } aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + (-aNormal[0]).ToString("f3", bz) + " " + (-aNormal[1]).ToString("f3", bz) + " " + (-aNormal[2]).ToString("f3", bz) + "\n"; textbuilder.Append(mline); } } // Write all UV (also with '0' as third value, for compatibility with some OBJ reader) if (saveUV) { for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) { swProgress.UpdateTitle("Exporting (write " + iv + "-th UV in .obj) ..."); } aVertexParams = (double[])swTessellation.GetVertexParams(iv); mline = "vt " + aVertexParams[0].ToString("f4", bz) + " " + aVertexParams[1].ToString("f4", bz) + " " + "0" + "\n"; textbuilder.Append(mline); } } // Loop over faces swFace = (Face2)swBody.GetFirstFace(); while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) { swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); } mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); // There should always be three fins per facet for (int iFinIdx = 0; iFinIdx < 3; iFinIdx++) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); // Three fins per face, two vertexes each fin, // only the 1st vertex of two is needed (because of sharing) if (saveUV) { mline += " " + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_nstride + 1); } else { mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + group_nstride + 1); } } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } swFace = (Face2)swBody.GetFirstFace(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles { while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) { swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); } mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); for (int iFinIdx = 2; iFinIdx >= 0; iFinIdx--) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); if (saveUV) { mline += " " + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); } else { mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); } } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } } group_vstride += swTessellation.GetVertexCount(); group_nstride += swTessellation.GetVertexCount(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets: two-sided triangles { group_nstride += swTessellation.GetVertexCount(); } } } // end loop on bodies } // not null body asciitext += textbuilder.ToString(); }
/// Convert a SolidWorks component to Wavefront OBJ mesh /// public static void Convert(Component2 swComp, ref string asciitext, bool saveUV, ref UserProgressBar swProgress) { StringBuilder textbuilder = new StringBuilder(); Body2 swBody = default(Body2); object[] vBodies = null; object[] vBodiesSolid = null; object[] vBodiesSheet = null; object vBodyInfo; int[] BodiesInfo = null; int j = 0; ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc(); vBodiesSolid = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); vBodiesSheet = (object[])swComp.GetBodies3((int)swBodyType_e.swSheetBody, out vBodyInfo); BodiesInfo = (int[])vBodyInfo; if (vBodiesSolid != null && vBodiesSheet == null) vBodies = vBodiesSolid; if (vBodiesSolid == null && vBodiesSheet != null) vBodies = vBodiesSheet; if (vBodiesSolid != null && vBodiesSheet != null) vBodies = vBodiesSheet.Concat(vBodiesSolid).ToArray(); // vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); if (vBodies != null) { int iNumBodies = vBodies.Length; int iNumSolidBodies = 0; int iNumSheetBodies = 0; int iNumTesselatedBodies = 0; if (iNumBodies >0) asciitext += "# Wavefront .OBJ file for tesselated shape: " + swComp.Name2 + " path: " + swModel.GetPathName() + "\n\n"; int group_vstride = 0; int group_nstride = 0; // Loop through bodies for (j = 0; j <= vBodies.Length - 1; j++) { swBody = (Body2)vBodies[j]; int nBodyType = (int)swBody.GetType(); if (nBodyType == (int)swBodyType_e.swSheetBody) iNumSheetBodies++; if (nBodyType == (int)swBodyType_e.swSolidBody) iNumSolidBodies++; if ((nBodyType == (int)swBodyType_e.swSheetBody || nBodyType == (int)swBodyType_e.swSolidBody) && !swBody.Name.StartsWith("COLL.") && swBody.Visible) { iNumTesselatedBodies++; CultureInfo bz = new CultureInfo("en-BZ"); //asciitext += "g body_" + iNumTesselatedBodies + "\n"; textbuilder.Append("g body_" + iNumTesselatedBodies + "\n"); Face2 swFace = null; Tessellation swTessellation = null; bool bResult = false; // Pass in null so the whole body will be tessellated swTessellation = (Tessellation)swBody.GetTessellation(null); // Set up the Tessellation object swTessellation.NeedFaceFacetMap = true; swTessellation.NeedVertexParams = true; swTessellation.NeedVertexNormal = true; swTessellation.ImprovedQuality = true; // How to handle matches across common edges swTessellation.MatchType = (int)swTesselationMatchType_e.swTesselationMatchFacetTopology; // Do it if (swProgress != null) swProgress.UpdateTitle("Exporting (tesselate process) ..."); bResult = swTessellation.Tessellate(); // Get the number of vertices and facets //System.Windows.Forms.MessageBox.Show("Body n." + j + " vert.num=" + swTessellation.GetVertexCount()); //Debug.Print("Number of vertices: " + swTessellation.GetVertexCount()); //Debug.Print("Number of facets: " + swTessellation.GetFacetCount()); // Now get the facet data per face int[] aFacetIds; int iNumFacetIds; int[] aFinIds; int[] aVertexIds; double[] aNormal; double[] aVertexCoords1; double[] aVertexCoords2; double[] aVertexParams; int numv = swTessellation.GetVertexCount(); // Write all vertexes string mline; for (int iv = 0; iv < numv; iv++) { if ((swProgress != null)&&(iv%200==0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th vertex in .obj) ..."); aVertexCoords1 = (double[])swTessellation.GetVertexPoint(iv); mline = "v " + (aVertexCoords1[0]*ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[1]*ChScale.L).ToString("f6", bz) + " " + (aVertexCoords1[2]*ChScale.L).ToString("f6", bz) + "\n"; textbuilder.Append(mline); } // Write all normals for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + aNormal[0].ToString("f3", bz) + " " + aNormal[1].ToString("f3", bz) + " " + aNormal[2].ToString("f3", bz) + "\n"; textbuilder.Append(mline); } if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th normal in .obj) ..."); aNormal = (double[])swTessellation.GetVertexNormal(iv); mline = "vn " + (-aNormal[0]).ToString("f3", bz) + " " + (-aNormal[1]).ToString("f3", bz) + " " + (-aNormal[2]).ToString("f3", bz) + "\n"; textbuilder.Append(mline); } // Write all UV (also with '0' as third value, for compatibility with some OBJ reader) if (saveUV) for (int iv = 0; iv < numv; iv++) { if ((swProgress != null) && (iv % 200 == 0)) swProgress.UpdateTitle("Exporting (write " + iv + "-th UV in .obj) ..."); aVertexParams = (double[])swTessellation.GetVertexParams(iv); mline = "vt " + aVertexParams[0].ToString("f4", bz) + " " + aVertexParams[1].ToString("f4", bz) + " " + "0" + "\n"; textbuilder.Append(mline); } // Loop over faces swFace = (Face2)swBody.GetFirstFace(); while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); // There should always be three fins per facet for (int iFinIdx = 0; iFinIdx < 3; iFinIdx++) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); // Three fins per face, two vertexes each fin, // only the 1st vertex of two is needed (because of sharing) if (saveUV) mline += " " + (aVertexIds[0] + group_vstride +1) + "/" + (aVertexIds[0] + group_vstride +1) + "/" + (aVertexIds[0] + group_nstride +1); else mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + group_nstride + 1); } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } swFace = (Face2)swBody.GetFirstFace(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets, save two-sided triangles while (swFace != null) { aFacetIds = (int[])swTessellation.GetFaceFacets(swFace); iNumFacetIds = aFacetIds.Length; for (int iFacetIdIdx = 0; iFacetIdIdx < iNumFacetIds; iFacetIdIdx++) { if ((swProgress != null) && (iFacetIdIdx % 100 == 0)) swProgress.UpdateTitle("Exporting (write " + iFacetIdIdx + "-th face in .obj) ..."); mline = "f"; aFinIds = (int[])swTessellation.GetFacetFins(aFacetIds[iFacetIdIdx]); for (int iFinIdx = 2; iFinIdx >= 0; iFinIdx--) { aVertexIds = (int[])swTessellation.GetFinVertices(aFinIds[iFinIdx]); if (saveUV) mline += " " + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + group_vstride + 1) + "/" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); else mline += " " + (aVertexIds[0] + group_vstride + 1) + "//" + (aVertexIds[0] + swTessellation.GetVertexCount() + group_nstride + 1); } mline += "\n"; textbuilder.Append(mline); } swFace = (Face2)swFace.GetNextFace(); } group_vstride += swTessellation.GetVertexCount(); group_nstride += swTessellation.GetVertexCount(); if (nBodyType == (int)swBodyType_e.swSheetBody) // for sheets: two-sided triangles group_nstride += swTessellation.GetVertexCount(); } } // end loop on bodies } // not null body asciitext += textbuilder.ToString(); }
public static bool rawRaysSeeComponentInCurrentConfig(Component2 component) { /* * see https://forum.solidworks.com/message/348151 */ List <IBody2> bodies = new List <IBody2>(); object vBodyInfo; object[] componentBodies = (object[])component.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo); for (int i = 0; i < componentBodies.Length; i++) { IBody2 tempBody = ((Body2)componentBodies[i]).ICopy(); tempBody.ApplyTransform(component.Transform2); bodies.Add(tempBody); } double[] rayVectorOrigins = camera.rayVectorOrigins(); double[] rayVectorDirections = camera.rayVectorDirections(); int numIntersectionsFound = (int)swDoc.RayIntersections((object)bodies.ToArray(), (object)rayVectorOrigins, (object)rayVectorDirections, (int)(swRayPtsOpts_e.swRayPtsOptsTOPOLS | swRayPtsOpts_e.swRayPtsOptsNORMALS), (double).0000001, (double).0000001); if (numIntersectionsFound == 0) { return(false); } double[] horrifyingReturn = (double[])swDoc.GetRayIntersectionsPoints(); for (int i = 0; i < horrifyingReturn.Length; i += 9) { double[] pt = new double[] { horrifyingReturn[i + 3], horrifyingReturn[i + 4], horrifyingReturn[i + 5] }; } int lengthOfOneReturn = 9; for (int i = 0; i < numIntersectionsFound; i++) { int rayIndex = (int)horrifyingReturn[i * lengthOfOneReturn + 1]; double x = horrifyingReturn[i * lengthOfOneReturn + 3]; double y = horrifyingReturn[i * lengthOfOneReturn + 4]; double z = horrifyingReturn[i * lengthOfOneReturn + 5]; double[] rayOrigin = camera.rayVectorSources().ElementAt(rayIndex).ArrayData; double[] rayDirection = camera.rayVectors().ElementAt(rayIndex).ArrayData; double[] hitPoint = new double[] { x, y, z }; if (!hitMainBodyBefore(rayOrigin, rayDirection, hitPoint) && !hitSomethingElseBefore(rayOrigin, rayDirection, hitPoint)) { if (visualize) { startSketch(); visualizeRay(mathUtils.CreateVector(rayDirection), mathUtils.CreatePoint(rayOrigin)); finishSketch(); } return(true); } } return(false); }
public void PythonTraverseFeatures_for_collshapes(Component2 swComp, long nLevel, ref string asciitext, int nbody, ref MathTransform chbodytransform, ref bool found_collisionshapes, Component2 swCompBase) { CultureInfo bz = new CultureInfo("en-BZ"); Feature swFeat; swFeat = (Feature)swComp.FirstFeature(); String bodyname = "body_" + nbody; MathTransform subcomp_transform = swComp.GetTotalTransform(true); MathTransform invchbody_trasform = (MathTransform)chbodytransform.Inverse(); MathTransform collshape_subcomp_transform = subcomp_transform.IMultiply(invchbody_trasform); // row-ordered transf. -> reverse mult.order! // Export collision shapes if (this.checkBox_collshapes.Checked) { object[] bodies; object bodyInfo; bodies = (object[])swComp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo); if (bodies != null) { // see if it contains some collision shape bool build_collision_model = false; for (int ib = 0; ib < bodies.Length; ib++) { Body2 swBody = (Body2)bodies[ib]; if (swBody.Name.StartsWith("COLL.")) build_collision_model = true; } if (build_collision_model) { if (!found_collisionshapes) { found_collisionshapes = true; // fetch SW attribute with Chrono parameters SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swCompBase.FindAttribute(this.mSWintegration.defattr_chbody, 0); if (myattr != null) { asciitext += "\n# Collision parameters \n"; double param_friction = ((Parameter)myattr.GetParameter("friction")).GetDoubleValue(); double param_restitution = ((Parameter)myattr.GetParameter("restitution")).GetDoubleValue(); double param_rolling_friction = ((Parameter)myattr.GetParameter("rolling_friction")).GetDoubleValue(); double param_spinning_friction = ((Parameter)myattr.GetParameter("spinning_friction")).GetDoubleValue(); double param_collision_envelope = ((Parameter)myattr.GetParameter("collision_envelope")).GetDoubleValue(); double param_collision_margin = ((Parameter)myattr.GetParameter("collision_margin")).GetDoubleValue(); int param_collision_family = (int)((Parameter)myattr.GetParameter("collision_family")).GetDoubleValue(); asciitext += String.Format(bz, "{0}.SetFriction({1:g});\n", bodyname, param_friction); if (param_restitution != 0) asciitext += String.Format(bz, "{0}.SetImpactC({1:g});\n", bodyname, param_restitution); if (param_rolling_friction != 0) asciitext += String.Format(bz, "{0}.SetRollingFriction({1:g});\n", bodyname, param_rolling_friction); if (param_spinning_friction != 0) asciitext += String.Format(bz, "{0}.SetSpinningFriction({1:g});\n", bodyname, param_spinning_friction); //if (param_collision_envelope != 0.03) asciitext += String.Format(bz, "{0}.GetCollisionModel().SetEnvelope({1:g});\n", bodyname, param_collision_envelope * ChScale.L); //if (param_collision_margin != 0.01) asciitext += String.Format(bz, "{0}.GetCollisionModel().SetSafeMargin({1:g});\n", bodyname, param_collision_margin * ChScale.L); if (param_collision_family != 0) asciitext += String.Format(bz, "{0}.GetCollisionModel().SetFamily({1});\n", bodyname, param_collision_family); } // clear model only at 1st subcomponent where coll shapes are found in features: asciitext += "\n# Collision shapes \n"; asciitext += String.Format(bz, "{0}.GetCollisionModel().ClearModel()\n", bodyname); } for (int ib = 0; ib < bodies.Length; ib++) { Body2 swBody = (Body2)bodies[ib]; if (swBody.Name.StartsWith("COLL.")) { bool rbody_converted = false; if (ConvertToCollisionShapes.SWbodyToSphere(swBody)) { Point3D center_l = new Point3D(); // in local subcomponent double rad = 0; ConvertToCollisionShapes.SWbodyToSphere(swBody, ref rad, ref center_l); Point3D center = SWTaskpaneHost.PointTransform(center_l, ref collshape_subcomp_transform); asciitext += String.Format(bz, "{0}.GetCollisionModel().AddSphere({1}, chrono.ChVectorD({2},{3},{4}))\n", bodyname, rad * ChScale.L, center.X * ChScale.L, center.Y * ChScale.L, center.Z * ChScale.L); rbody_converted = true; } if (ConvertToCollisionShapes.SWbodyToBox(swBody)) { Point3D vC_l = new Point3D(); Vector3D eX_l = new Vector3D(); Vector3D eY_l = new Vector3D(); Vector3D eZ_l = new Vector3D(); ConvertToCollisionShapes.SWbodyToBox(swBody, ref vC_l, ref eX_l, ref eY_l, ref eZ_l); Point3D vC = SWTaskpaneHost.PointTransform(vC_l, ref collshape_subcomp_transform); Vector3D eX = SWTaskpaneHost.DirTransform(eX_l, ref collshape_subcomp_transform); Vector3D eY = SWTaskpaneHost.DirTransform(eY_l, ref collshape_subcomp_transform); Vector3D eZ = SWTaskpaneHost.DirTransform(eZ_l, ref collshape_subcomp_transform); double hsX = eX.Length * 0.5; double hsY = eY.Length * 0.5; double hsZ = eZ.Length * 0.5; Point3D vO = vC + 0.5 * eX + 0.5 * eY + 0.5 * eZ; Vector3D Dx = eX; Dx.Normalize(); Vector3D Dy = eY; Dy.Normalize(); Vector3D Dz = Vector3D.CrossProduct(Dx, Dy); asciitext += String.Format(bz, "mr = chrono.ChMatrix33D()\n"); asciitext += String.Format(bz, "mr[0,0]={0}; mr[1,0]={1}; mr[2,0]={2} \n", Dx.X, Dx.Y, Dx.Z); asciitext += String.Format(bz, "mr[0,1]={0}; mr[1,1]={1}; mr[2,1]={2} \n", Dy.X, Dy.Y, Dy.Z); asciitext += String.Format(bz, "mr[0,2]={0}; mr[1,2]={1}; mr[2,2]={2} \n", Dz.X, Dz.Y, Dz.Z); asciitext += String.Format(bz, "{0}.GetCollisionModel().AddBox({1},{2},{3},chrono.ChVectorD({4},{5},{6}),mr)\n", bodyname, hsX * ChScale.L, hsY * ChScale.L, hsZ * ChScale.L, vO.X * ChScale.L, vO.Y * ChScale.L, vO.Z * ChScale.L); rbody_converted = true; } if (ConvertToCollisionShapes.SWbodyToCylinder(swBody)) { Point3D p1_l = new Point3D(); Point3D p2_l = new Point3D(); double rad = 0; ConvertToCollisionShapes.SWbodyToCylinder(swBody, ref p1_l, ref p2_l, ref rad); Point3D p1 = SWTaskpaneHost.PointTransform(p1_l, ref collshape_subcomp_transform); Point3D p2 = SWTaskpaneHost.PointTransform(p2_l, ref collshape_subcomp_transform); Vector3D Dy = p1 - p2; Dy.Normalize(); double hsY = (p1 - p2).Length * 0.5; double hsZ = rad; double hsX = rad; Point3D vO = p1 + 0.5 * (p2 - p1); Vector3D Dx = new Vector3D(); if (Dy.X < 0.9) { Vector3D Dtst = new Vector3D(1, 0, 0); Dx = Vector3D.CrossProduct(Dtst, Dy); } else { Vector3D Dtst = new Vector3D(0, 1, 0); Dx = Vector3D.CrossProduct(Dtst, Dy); } Vector3D Dz = Vector3D.CrossProduct(Dx, Dy); asciitext += String.Format(bz, "mr = chrono.ChMatrix33D()\n"); asciitext += String.Format(bz, "mr[0,0]={0}; mr[1,0]={1}; mr[2,0]={2} \n", Dx.X, Dx.Y, Dx.Z); asciitext += String.Format(bz, "mr[0,1]={0}; mr[1,1]={1}; mr[2,1]={2} \n", Dy.X, Dy.Y, Dy.Z); asciitext += String.Format(bz, "mr[0,2]={0}; mr[1,2]={1}; mr[2,2]={2} \n", Dz.X, Dz.Y, Dz.Z); asciitext += String.Format(bz, "{0}.GetCollisionModel().AddCylinder({1},{2},{3},chrono.ChVectorD({4},{5},{6}),mr)\n", bodyname, hsX * ChScale.L, hsZ * ChScale.L, hsY * ChScale.L, vO.X * ChScale.L, vO.Y * ChScale.L, vO.Z * ChScale.L); // note order hsX-Z-Y rbody_converted = true; } if (ConvertToCollisionShapes.SWbodyToConvexHull(swBody, 30) && !rbody_converted) { Point3D[] vertexes = new Point3D[1]; // will be resized by SWbodyToConvexHull ConvertToCollisionShapes.SWbodyToConvexHull(swBody, ref vertexes, 30); if (vertexes.Length > 0) { asciitext += String.Format(bz, "pt_vect = chrono.vector_ChVectorD()\n"); for (int iv = 0; iv < vertexes.Length; iv++) { Point3D vert_l = vertexes[iv]; Point3D vert = SWTaskpaneHost.PointTransform(vert_l, ref collshape_subcomp_transform); asciitext += String.Format(bz, "pt_vect.push_back(chrono.ChVectorD({0},{1},{2}))\n", vert.X * ChScale.L, vert.Y * ChScale.L, vert.Z * ChScale.L); } asciitext += String.Format(bz, "{0}.GetCollisionModel().AddConvexHull(pt_vect)\n", bodyname); } } } // end dealing with a collision shape } // end solid bodies traversal for converting to coll.shapes } // end if build_collision_model } } // end collision shapes export }
public void PythonTraverseComponent_for_visualizationshapes(Component2 swComp, long nLevel, ref string asciitext, int nbody, ref int nvisshape, Component2 chbody_comp) { CultureInfo bz = new CultureInfo("en-BZ"); object[] bodies; object bodyInfo; bodies = (object[])swComp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo); if (bodies != null) if (bodies.Length > 0) { // Export the component shape to a .OBJ file representing its SW body(s) nvisshape += 1; string bodyname = "body_" + nbody; string shapename = "body_" + nbody + "_" + nvisshape; string obj_filename = this.save_dir_shapes + "\\" + shapename + ".obj"; ModelDoc2 swCompModel = (ModelDoc2)swComp.GetModelDoc(); if (!this.saved_shapes.ContainsKey(swCompModel.GetPathName())) { try { FileStream ostream = new FileStream(obj_filename, FileMode.Create, FileAccess.ReadWrite); StreamWriter writer = new StreamWriter(ostream); //, new UnicodeEncoding()); string asciiobj = ""; if (this.swProgress != null) this.swProgress.UpdateTitle("Exporting " + swComp.Name2 + " (tesselate) ..."); // Write the OBJ converted visualization shapes: TesselateToObj.Convert(swComp, ref asciiobj, this.checkBox_saveUV.Checked, ref this.swProgress); writer.Write(asciiobj); writer.Flush(); ostream.Close(); this.saved_shapes.Add(swCompModel.GetPathName(), shapename); } catch (Exception) { System.Windows.Forms.MessageBox.Show("Cannot write to file: " + obj_filename); } } else { // reuse the already-saved shape name shapename = (String)saved_shapes[swCompModel.GetPathName()]; } asciitext += String.Format(bz, "\n# Visualization shape \n", bodyname); asciitext += String.Format(bz, "{0}_shape = chrono.ChObjShapeFile() \n", shapename); asciitext += String.Format(bz, "{0}_shape.SetFilename(shapes_dir +'{0}.obj') \n", shapename); object foo = null; double[] vMatProperties = (double[])swComp.GetMaterialPropertyValues2((int)swInConfigurationOpts_e.swThisConfiguration, foo); if (vMatProperties != null) if (vMatProperties[0] != -1) { asciitext += String.Format(bz, "{0}_shape.SetColor(chrono.ChColor({1},{2},{3})) \n", shapename, vMatProperties[0], vMatProperties[1], vMatProperties[2]); asciitext += String.Format(bz, "{0}_shape.SetFading({1}) \n", shapename, vMatProperties[7]); } MathTransform absframe_chbody = chbody_comp.GetTotalTransform(true); MathTransform absframe_shape = swComp.GetTotalTransform(true); MathTransform absframe_chbody_inv = absframe_chbody.IInverse(); MathTransform relframe_shape = absframe_shape.IMultiply(absframe_chbody_inv); // row-ordered transf. -> reverse mult.order! double[] amatr = (double[])relframe_shape.ArrayData; double[] quat = GetQuaternionFromMatrix(ref relframe_shape); asciitext += String.Format(bz, "{0}_level = chrono.ChAssetLevel() \n", shapename); asciitext += String.Format(bz, "{0}_level.GetFrame().SetPos(chrono.ChVectorD({1},{2},{3})) \n", shapename, amatr[9] *ChScale.L, amatr[10]*ChScale.L, amatr[11]*ChScale.L); asciitext += String.Format(bz, "{0}_level.GetFrame().SetRot(chrono.ChQuaternionD({1},{2},{3},{4})) \n", shapename, quat[0], quat[1], quat[2], quat[3]); asciitext += String.Format(bz, "{0}_level.GetAssets().push_back({0}_shape) \n", shapename); asciitext += String.Format(bz, "{0}.GetAssets().push_back({1}_level) \n", bodyname, shapename); } // Recursive scan of subcomponents Component2 swChildComp; object[] vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; if (swChildComp.Visible == (int)swComponentVisibilityState_e.swComponentVisible) PythonTraverseComponent_for_visualizationshapes(swChildComp, nLevel + 1, ref asciitext, nbody, ref nvisshape, chbody_comp); } }
public void PythonTraverseComponent_for_massbodies(Component2 swComp, ref object[] obodies, ref int addedb) { // Add bodies of this component to the list object[] bodies; object bodyInfo; bodies = (object[])swComp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo); if (bodies != null) { // note: some bodies might be collision shapes and must not enter the mass computation: for (int ib = 0; ib < bodies.Length; ib++) { Body2 abody = (Body2)bodies[ib]; if (!(abody.Name.StartsWith("COLL."))) { obodies[addedb] = bodies[ib]; addedb += 1; } } } // Recursive scan of subcomponents Component2 swChildComp; object[] vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; PythonTraverseComponent_for_massbodies(swChildComp, ref obodies, ref addedb); } }