Scenekit Shape Between 4 Points

Scenekit shape between 4 points

So the answer, at least my solution is to use SCNGeometry triangles. I wanted a square (rather than a cube) to act as a wall in Augmented Reality so I simply built 2 triangles using the 4 nodes that mapped the 4 corners of a wall.

The class to build the triangle:

extension SCNGeometry {

class func triangleFrom(vector1: SCNVector3, vector2: SCNVector3, vector3: SCNVector3) -> SCNGeometry {

let indices: [Int32] = [0, 1, 2]

let source = SCNGeometrySource(vertices: [vector1, vector2, vector3])

let element = SCNGeometryElement(indices: indices, primitiveType: .triangles)

return SCNGeometry(sources: [source], elements: [element])
}
}

The points for the 2 triangles are [p1, p2, p4] and [p1, p3, p4] called using the following:

let thirdPoint = firstPoint.clone()
thirdPoint.position = SCNVector3Make(thirdPoint.position.x,
thirdPoint.position.y + Float(1.5), thirdPoint.position.z)
sceneView.scene.rootNode.addChildNode(thirdPoint)

let fourthPoint = secondPoint.clone()
fourthPoint.position = SCNVector3Make(fourthPoint.position.x,
fourthPoint.position.y + Float(1.5), fourthPoint.position.z)
sceneView.scene.rootNode.addChildNode(fourthPoint)

let triangle = SCNGeometry.triangleFrom(vector1: firstPoint.position, vector2: secondPoint.position, vector3: fourthPoint.position)
let triangleNode = SCNNode(geometry: triangle)
triangleNode.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
triangleNode.geometry?.firstMaterial?.isDoubleSided = true
sceneView.scene.rootNode.addChildNode(triangleNode)

let triangle2 = SCNGeometry.triangleFrom(vector1: firstPoint.position, vector2: thirdPoint.position, vector3: fourthPoint.position)
let triangle2Node = SCNNode(geometry: triangle2)
triangle2Node.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
triangle2Node.geometry?.firstMaterial?.isDoubleSided = true
sceneView.scene.rootNode.addChildNode(triangle2Node)

This is all based on creating 2 initial nodes by selecting the bottom 2 points of a wall in ARKit.

Hope that makes sense to anybody else searching for a similar answer.

EDIT: Adding a Material

Here's a slightly different extension and the code to add a material to it, the end result of a wall remains the same:

extension SCNGeometry {

class func Quad() -> SCNGeometry {

let verticesPosition = [
SCNVector3(x: -0.242548823, y: -0.188490361, z: -0.0887458622),
SCNVector3(x: -0.129298389, y: -0.188490361, z: -0.0820985138),
SCNVector3(x: -0.129298389, y: 0.2, z: -0.0820985138),
SCNVector3(x: -0.242548823, y: 0.2, z: -0.0887458622)
]

let textureCord = [
CGPoint(x: 1, y: 1),
CGPoint(x: 0, y: 1),
CGPoint(x: 0, y: 0),
CGPoint(x: 1, y: 0),
]

let indices: [CInt] = [
0, 2, 3,
0, 1, 2
]

let vertexSource = SCNGeometrySource(vertices: verticesPosition)
let srcTex = SCNGeometrySource(textureCoordinates: textureCord)
let date = NSData(bytes: indices, length: MemoryLayout<CInt>.size * indices.count)

let scngeometry = SCNGeometryElement(data: date as Data,
primitiveType: SCNGeometryPrimitiveType.triangles, primitiveCount: 2,
bytesPerIndex: MemoryLayout<CInt>.size)

let geometry = SCNGeometry(sources: [vertexSource,srcTex],
elements: [scngeometry])

return geometry

}

}

Then simply call it in viewDidLoad() and apply a material

let scene = SCNScene()

let quad = SCNGeometry.Quad()

let (min, max) = quad.boundingBox

let width = CGFloat(max.x - min.x)
let height = CGFloat(max.y - min.y)

quad.firstMaterial?.diffuse.contents = UIImage(named: "wallpaper.jpg")
quad.firstMaterial?.diffuse.contentsTransform = SCNMatrix4MakeScale(Float(width), Float(height), 1)
quad.firstMaterial?.diffuse.wrapS = SCNWrapMode.repeat
quad.firstMaterial?.diffuse.wrapT = SCNWrapMode.repeat

let node = SCNNode()
node.geometry = quad
scene.rootNode.addChildNode(node)

sceneView.scene = scene

SceneKit Object between two points

I've good news for you ! You can link two points and put a SCNNode on this Vector !

Take this and enjoy drawing line between two points !

class   CylinderLine: SCNNode
{
init( parent: SCNNode,//Needed to line to your scene
v1: SCNVector3,//Source
v2: SCNVector3,//Destination
radius: CGFloat,// Radius of the cylinder
radSegmentCount: Int, // Number of faces of the cylinder
color: UIColor )// Color of the cylinder
{
super.init()

//Calcul the height of our line
let height = v1.distance(v2)

//set position to v1 coordonate
position = v1

//Create the second node to draw direction vector
let nodeV2 = SCNNode()

//define his position
nodeV2.position = v2
//add it to parent
parent.addChildNode(nodeV2)

//Align Z axis
let zAlign = SCNNode()
zAlign.eulerAngles.x = CGFloat(M_PI_2)

//create our cylinder
let cyl = SCNCylinder(radius: radius, height: CGFloat(height))
cyl.radialSegmentCount = radSegmentCount
cyl.firstMaterial?.diffuse.contents = color

//Create node with cylinder
let nodeCyl = SCNNode(geometry: cyl )
nodeCyl.position.y = CGFloat(-height/2)
zAlign.addChildNode(nodeCyl)

//Add it to child
addChildNode(zAlign)

//set constraint direction to our vector
constraints = [SCNLookAtConstraint(target: nodeV2)]
}

override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

private extension SCNVector3{
func distance(receiver:SCNVector3) -> Float{
let xd = receiver.x - self.x
let yd = receiver.y - self.y
let zd = receiver.z - self.z
let distance = Float(sqrt(xd * xd + yd * yd + zd * zd))

if (distance < 0){
return (distance * -1)
} else {
return (distance)
}
}
}

Draw SceneKit object between two points

Both solutions mentioned above work very well and I can contribute third solution to this question.

//extension code starts

func normalizeVector(_ iv: SCNVector3) -> SCNVector3 {
let length = sqrt(iv.x * iv.x + iv.y * iv.y + iv.z * iv.z)
if length == 0 {
return SCNVector3(0.0, 0.0, 0.0)
}

return SCNVector3( iv.x / length, iv.y / length, iv.z / length)

}

extension SCNNode {

func buildLineInTwoPointsWithRotation(from startPoint: SCNVector3,
to endPoint: SCNVector3,
radius: CGFloat,
color: UIColor) -> SCNNode {
let w = SCNVector3(x: endPoint.x-startPoint.x,
y: endPoint.y-startPoint.y,
z: endPoint.z-startPoint.z)
let l = CGFloat(sqrt(w.x * w.x + w.y * w.y + w.z * w.z))

if l == 0.0 {
// two points together.
let sphere = SCNSphere(radius: radius)
sphere.firstMaterial?.diffuse.contents = color
self.geometry = sphere
self.position = startPoint
return self

}

let cyl = SCNCylinder(radius: radius, height: l)
cyl.firstMaterial?.diffuse.contents = color

self.geometry = cyl

//original vector of cylinder above 0,0,0
let ov = SCNVector3(0, l/2.0,0)
//target vector, in new coordination
let nv = SCNVector3((endPoint.x - startPoint.x)/2.0, (endPoint.y - startPoint.y)/2.0,
(endPoint.z-startPoint.z)/2.0)

// axis between two vector
let av = SCNVector3( (ov.x + nv.x)/2.0, (ov.y+nv.y)/2.0, (ov.z+nv.z)/2.0)

//normalized axis vector
let av_normalized = normalizeVector(av)
let q0 = Float(0.0) //cos(angel/2), angle is always 180 or M_PI
let q1 = Float(av_normalized.x) // x' * sin(angle/2)
let q2 = Float(av_normalized.y) // y' * sin(angle/2)
let q3 = Float(av_normalized.z) // z' * sin(angle/2)

let r_m11 = q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3
let r_m12 = 2 * q1 * q2 + 2 * q0 * q3
let r_m13 = 2 * q1 * q3 - 2 * q0 * q2
let r_m21 = 2 * q1 * q2 - 2 * q0 * q3
let r_m22 = q0 * q0 - q1 * q1 + q2 * q2 - q3 * q3
let r_m23 = 2 * q2 * q3 + 2 * q0 * q1
let r_m31 = 2 * q1 * q3 + 2 * q0 * q2
let r_m32 = 2 * q2 * q3 - 2 * q0 * q1
let r_m33 = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3

self.transform.m11 = r_m11
self.transform.m12 = r_m12
self.transform.m13 = r_m13
self.transform.m14 = 0.0

self.transform.m21 = r_m21
self.transform.m22 = r_m22
self.transform.m23 = r_m23
self.transform.m24 = 0.0

self.transform.m31 = r_m31
self.transform.m32 = r_m32
self.transform.m33 = r_m33
self.transform.m34 = 0.0

self.transform.m41 = (startPoint.x + endPoint.x) / 2.0
self.transform.m42 = (startPoint.y + endPoint.y) / 2.0
self.transform.m43 = (startPoint.z + endPoint.z) / 2.0
self.transform.m44 = 1.0
return self
}
}

//extension ended.

//in your code, you can like this.
let twoPointsNode1 = SCNNode()
scene.rootNode.addChildNode(twoPointsNode1.buildLineInTwoPointsWithRotation(
from: SCNVector3(1,-1,3), to: SCNVector3( 7,11,7), radius: 0.2, color: .cyan))
//end

you can reference http://danceswithcode.net/engineeringnotes/quaternions/quaternions.html

BTW, you will get same result when you use a cylinder to make a line between two points from above 3 methods. But indeed, they will have different normal lines. In another words, if you use box between two points, sides of box, except top and bottom, will face different direction from above 3 methods.

let me know pls if you need further explanation.

How to create a angled plane given an array of scnvector3 points

Here is what I ended up doing instead of using SCNPlane (in this case a triangle.) This will create a custom geometry with given points. For the indices, you mark which order you want to connect the points, and then to make it visible from both sides of the plane, you draw the reverse order.

    let vertices: [SCNVector3] = [SCNVector3(0, 1, 0),
SCNVector3(-0.5, 0, 0.5),
SCNVector3(0.5, 0, 0.5)]

let source = SCNGeometrySource(vertices: vertices)

let indices: [UInt16] = [0, 1, 2,
2, 1, 0,]

let element = SCNGeometryElement(indices: indices, primitiveType: .triangles)

let geometry = SCNGeometry(sources: [source], elements: [element])
geometry.firstMaterial?.diffuse.contents = NSColor.green
let node = SCNNode(geometry: geometry)
let scnView = self.view as! SCNView

scnView.scene?.rootNode.addChildNode(node)

SceneKit – Drawing a line between two points

There are lots of ways to do this.

As noted, your custom geometry approach has some disadvantages. You should be able to correct the problem of it being invisible from one side by giving its material the doubleSided property. You still may have issues with it being two-dimensional, though.

You could also modify your custom geometry to include more triangles, so you get a tube shape with three or more sides instead of a flat rectangle. Or just have two points in your geometry source, and use the SCNGeometryPrimitiveTypeLine geometry element type to have Scene Kit draw a line segment between them. (Though you won't get as much flexibility in rendering styles with line drawing as with shaded polygons.)

You can also use the SCNCylinder approach you mentioned (or any of the other built-in primitive shapes). Remember that geometries are defined in their own local (aka Model) coordinate space, which Scene Kit interprets relative to the coordinate space defined by a node. In other words, you can define a cylinder (or box or capsule or plane or whatever) that's 1.0 units wide in all dimensions, then use the rotation/scale/position or transform of the SCNNode containing that geometry to make it long, thin, and stretching between the two points you want. (Also note that since your line is going to be pretty thin, you can reduce the segmentCounts of whichever built-in geometry you're using, because that much detail won't be visible.)

Yet another option is the SCNShape class that lets you create an extruded 3D object from a 2D Bézier path. Working out the right transform to get a plane connecting two arbitrary points sounds like some fun math, but once you do it you could easily connect your points with any shape of line you choose.

Add shape to sphere surface in SceneKit

If you want to map 2D content into the surface of a 3D SceneKit object, and have the 2D content be dynamic/interactive, one of the easiest solutions is to use SpriteKit for the 2D content. You can set your sphere's diffuse contents to an SKScene, and create/position/decorate SpriteKit nodes in that scene to arrange them on the face of the sphere.

If you want to have this content respond to tap events... Using hitTest in your SceneKit view gets you a SCNHitTestResult, and from that you can get texture coordinates for the hit point on the sphere. From texture coordinates you can convert to SKScene coordinates and spawn nodes, run actions, or whatever.

For further details, your best bet is probably Apple's SceneKitReel sample code project. This is the demo that introduced SceneKit for iOS at WWDC14. There's a "slide" in that demo where paint globs fly from the camera at a spinning torus and leave paint splashes where they hit it — the torus has a SpriteKit scene as its material, and the trick for leaving splashes on collisions is basically the same hit test -> texture coordinate -> SpriteKit coordinate approach outlined above.



Related Topics



Leave a reply



Submit