Post

Replies

Boosts

Views

Activity

Reply to Triangle Intersection in 3D Space
Sorry that I could not respond to your comment earlier. I had to learn for an exam. If someone finds some wrong math or wrong results please let me know. import Foundation import simd // Dfinition of the two planes (Q,R) let Q = (SIMD3<Double>(0,5,0.00000000000000001),SIMD3<Double>(5,1,0),SIMD3<Double>(3, 1, 0)) // first triangle let R = (SIMD3<Double>(1,2,4),SIMD3<Double>(3,1,6),SIMD3<Double>(2,4,-2)) // That are the same points as in the answer above // In this example you can not set P.z = 0 because the line is paralle to xy // normals // normalized to get a better comperiosion let NQ = normalize(cross((Q.1 - Q.0),(Q.2 - Q.0))) let NR = normalize(cross((R.1 - R.0),(R.2 - R.0))) // Plane equtions // x -> a , y -> b, z -> c // That is the normal to plane equtions variable convertion ((a,b,c) are used normally) // D of first plane let DQ = -(NQ.x*Q.0.x + NQ.y*Q.0.y + NQ.z*Q.0.z) // D of second plane let DR = -(NR.x*R.0.x + NR.y*R.0.y + NR.z*R.0.z) // Find P on Vektor V // P.z = 0 let x = (NQ.y*DR - DQ*NR.x)/(NQ.x*NR.y - NQ.y*NR.x) // took to plane equtions and removed z and solved for x and y let y = -(NR.x*x+DR) / NR.y // computes y of the Point P let P = SIMD3<Double>(x,y,0) // That is a point in the Intesectionline of the two planes //Linevector let VI = cross(NQ,NR) // VI is normal on both palne normlas // Lines on the Vektor of triangle Q let IntersectionLine = [(t:computesides(P,VI,Q.0,Q.1),first: true),(t:computesides(P,VI,Q.0,Q.2),first: true),(t:computesides(P,VI,Q.2,Q.1),first: true),(t:computesides(P,VI,R.0,R.1),first: false),(t:computesides(P,VI,R.0,R.2),first: false),(t:computesides(P,VI,R.2,R.1),first: false)] var UnwrapedLine = IntersectionLine.filter { $0.t != nil} // No nil ones left if UnwrapedLine.count != 4 { print("No Intersection")} UnwrapedLine.sort { $0.t! < $1.t!} // There should be no nils left if UnwrapedLine[0].first == UnwrapedLine[1].first {    print("Linesegments do not intersect") } else {    print("Line: \(P+VI*UnwrapedLine[0].t!) to \(P+VI*UnwrapedLine[1].t!) )") } func computesides(_ P: SIMD3<Double>,_ IV: SIMD3<Double>,_ VS: SIMD3<Double>,_ VE: SIMD3<Double>) -> Double? { // This func returns the distance to the Point P in the form of a Vector    let v = VE - VS // v for Vector    let s = (P.x * IV.y-P.y*IV.x+IV.x*VS.y-IV.y*VS.x)/(IV.y*v.x-IV.x*v.y) // Scalar shapeedge of v    if s > 1 || s < 0 {        print("No Intersection with the plane")        return nil    }    let t = (VS.x+v.x*s-P.x)/IV.x // it can be solved with x,y or z//P+IV*t = VS+v*s // (VS+v*s-P)/IV return t } Thanks for your code above.
Topic: Programming Languages SubTopic: Swift Tags:
Nov ’21