SceneKit Tutorial Half 2 – iOS Growth


Let’s proceed to have a look at the functionalities and APIs supplied by SceneKit. In a earlier tutorial, I highlighted a few of the fundamental courses you should utilize to create and render a 3D scene and add 3D objects to the scene utilizing the builtin shapes. On this second half tutorial, we’re going to see methods to deal with the looks of a node. The knowledge offered on this put up and the earlier one is related if you’re constructing ARKit purposes, so I counsel you to evaluation the ideas highlighted in Half I and verify the brand new matters offered right here.

Geometry

An SCNGeometry object offers the seen a part of a node. As proven in Half I of this tutorial, SceneKit offers builders with some fundamental 3D shapes, reminiscent of containers, spheres, cones, planes, and extra. You place and orient a geometry in a scene by attaching it to an occasion of an SCNNode and utilizing the place and the orientation of the node.

Making a geometry

SceneKit permits to create a geometry in numerous methods. The commonest strategy is to load the geometry from a scene file created utilizing exterior 3D authoring instruments. The explanation for that’s that SceneKit will not be actually a 3D modeling device. So, if you wish to construct complicated 3D fashions on your apps, one of the best strategy is to make use of Cinema4D, Maya, Modo, and so forth. I personally use Cheetah3D by MW3D-Options. This device is very easy to be taught and exports to completely different 3D file codecs and certainly one of them is Collada (DAE) very talked-about for iOS and cell platforms.

Geometries could be created through the use of and customizing SceneKit’s built-in primitive shapes (SCNBox, SCNSphere, SCNCone, and so on.) as I highlighted within the earlier put up.

You too can create geometries from vertex information. The floor of a geometry could be obtained connecting collectively an enormous assortment of 3D factors (vertexes) utilizing triangles. Basically, the vertexes related to a geometry are immutable, however SceneKit offers a number of methods to switch (animate) them. For instance, you should utilize an SCNMorpher or SCNSkinner object to deform a geometry’s floor, or run animations created in an exterior 3D authoring device and loaded from a scene file. You too can use strategies within the SCNShadable protocol so as to add customized GLSL or Metallic shaders that alter SceneKit’s rendering of a geometry.

A number of nodes can reference the identical geometry object, permitting it to look at completely different positions in a scene.

Customized geometries

If you wish to construct a customized geometry programmatically, you should utilize the init(sources:components:) technique and supply the geometry sources and geometry components.

Geometry supply

A geometry supply is an occasion of the SCNGeometrySource class. It’s a container for vertex information forming a part of the definition for a three-dimensional object. You create a geometry supply utilizing one of many following initializers:

Let’s give a take a look at the primary init of the above record. This init technique takes an occasion of a Knowledge factor as the primary argument (NSData if you’re engaged on Goal-C). The information is a group of values representing completely different kind of knowledge. The kind of every information factor is outlined by the second argument (semantic) of the init technique. SceneKit affords the next semantic sorts (outlined within the SCNGeometrySource.Semantic enumeration):

  • vertex defines that the information argument incorporates the place (x, y, and z) of every vertex. Vertex place information is often an array of 3- or 4-component vector (SCNVector3 or simd_float3 or SCNVector4 or simd_float4);
  • regular defines that the information argument incorporates the floor regular vector at every vertex within the geometry. Vertex regular information is often an array of 3- or 4-component vectors;
  • colour defines that the information argument incorporates the colour for every vertex within the geometry. Vertex colour information is often an array of 3- or 4-component vectors;
  • texcoord defines that the information argument incorporates texture mapping coordinates for every vertex within the geometry. In contrast to different semantics, a geometry could include a number of sources for texture coordinates – every corresponds to a separate mappingChannel quantity that you should utilize when associating textured supplies. Texture coordinate information is often an array of two-component vectors (simd_float2);
  • tangent defines that the information argument incorporates the floor tangent vector at every vertex within the geometry. SceneKit makes use of this info to compute superior lighting results on the floor. Vertex tangent information is often an array of 3- or 4-component vectors;
  • vertexCrease defines that the information argument incorporates crease information for every vertex within the geometry. SceneKit makes use of this info to find out the sharpness of corners and smoothness of surfaces while you change a geometry’s subdivisionLevel property. Vertex crease information is an array of scalar floating-point values, the place every worth determines the smoothness or sharpness of the corresponding vertex. A price of 0.0 specifies a totally smoothed nook, and a worth of 10.0 or better specifies an infinitely sharp level.
  • edgeCrease defines that the information argument incorporates crease information for every vertex within the geometry. SceneKit makes use of this info to find out the sharpness of edges and smoothness of surfaces while you change a geometry’s subdivisionLevel property. Edge crease information is an array of scalar floating-point values, the place every worth determines the smoothness or sharpness of the sting recognized by the primitive on the corresponding index within the geometry’s SceneKit Constants geometry factor. A price of 0.0 specifies a totally smoothed edge, and a worth of 10.0 or better specifies an infinitely sharp edge.
  • boneWeights defines that the information argument incorporates skeletal animation information for every vertex within the geometry. SceneKit makes use of this info to find out how a lot a vertex’s place is influenced by the positions of bone nodes within the skeleton. I’ll cowl Skeletal animations in a future put up. You’ll find extra info within the SCNSkinner class description.
  • boneIndices defines that the information argument incorporates skeletal animation information for every vertex within the geometry. SceneKit makes use of this info to find out which bone nodes within the skeleton have an effect on the conduct of every vertex.

The third argument within the above init technique is an integer representing the variety of components offered on the information argument. The usesFloatComponents argument is a boolean specifying that the information are floats (extra accuracy) or integers (higher efficiency). The componentsPerVector defines what number of elements every factor of the information argument has. The bytesPerComponent defines the dimensions, in bytes, of every vector element of the information argument. The offset argument defines an offset, in bytes, from the start of the information to the primary vector element for use within the geometry supply. Lastly, the stride argument defines the variety of bytes from every vector to the subsequent within the information. You should utilize the offset and stride parameters collectively to interleave information for a number of geometry sources in the identical array, bettering rendering efficiency.

The remaining init strategies are a simplified model of the primary init technique, so I cannot undergo the main points. Nevertheless, I wish to point out the second init technique that represents a small variation of the primary one. This technique is essential while you work with Metallic, as a result of it takes a Metallic buffer (MTLBuffer) as argument as a substitute of a Knowledge occasion.

Geometry factor

A geometry factor is a container for indices describing how vertices are linked collectively to outline the identical three-dimensional object. You instantiate a geometry factor object utilizing one of many following init strategies:

The primary init technique requires a listing of indices organized in a Knowledge occasion. The second argument (primitiveType) defines the kind of drawing primitives connecting the vertexes. The drawing primitives are outlined within the SCNGeometryPrimitiveType enumeration:

  • level: The geometry factor’s information is a sequence of unconnected factors;
  • line: The geometry factor’s information is a sequence of line segments, with every line phase described by two new vertices;
  • triangles: The geometry factor’s information is a sequence of triangles, with every triangle described by three new vertices;
  • triangleStrip: The geometry factor’s information is a sequence of triangles, with every triangle described by one new vertex and two vertices from the earlier triangle; and
  • polygon: Launched in iOS 10.

Instance of a customized geometry

Let’s see methods to construct a customized geometry. Launch Xcode and create a single view utility. Title it CustomGeometry. Open the Principal.storyboard file and add a scene equipment view to the primary view of the view controller. Add constraints to the protected space. Now, open the ViewController.swift file and add the next code:

Join the outlet to the scene equipment view in Interface Builder. Now, let’s add a brand new SceneKit scene file to our challenge and title it scene.scn. Add a brand new Group to the challenge and transfer the scene.scn file within the new group. Then rename the group artwork.scnassets. Now, edit the viewDidLoad() technique within the following manner:

The generateIcosahedron() technique does all of the work:

If you wish to enhance the road width, you should utilize the scene renderer to take action. Add the SCNSceneRendererDelegate to the view controller and make the view controller the delegate of the scene renderer:

We are able to additionally add colours to every vertex. Within the generateIcosahedron() technique, add the next code after you generate the geometry supply vertexSource.

Lastly, edit the final line of the generateIcosahedron() technique on this manner:

Construct and run and you need to see one thing like the next determine.

Figure 1. Custom geometry.
Determine 1. Customized geometry.

In a future put up, we are going to see methods to use Metallic shaders to switch this form in realtime.

Lights and Supplies

When constructing a 3D scene in SceneKit, you normally create nodes with their very own geometry. To make the scene look lifelike, it’s important to add two vital elements to your scene: supplies and lights. Supplies outline the looks of the geometry’s floor when rendered. Lights illuminate and have an effect on the looks of a scene. Each factor are essential and should be outlined. The ultimate look of the scene is obtained by how lights and supplies affect one another.

Lights

Gentle simulation is a really complicated matter in laptop graphics. I’ll attempt right here to simplify the ideas. Gentle is a selected form of electromagnetic radiation of a frequency that may be detected by the human eye. A light-weight begins from its supply (an object emitting gentle – solar, gentle bulb, and so on.). Then, the sunshine travels via a medium (air, area, glass, water or any materials in a position to transmit the sunshine) till it reaches a floor. When it reaches a floor, a part of the sunshine is mirrored and a part of it’s transmitted (absorbed by the floor).

In SceneKit, a lightweight supply is represented by an occasion of an SCNLight class. You create a lightweight object after which connect it to a node to light up the scene. SceneKit offers various kinds of gentle sources:

  • ambient gentle illuminates the scene from all instructions. As a result of the depth of sunshine from an ambient supply is identical in all places within the scene, its place and route haven’t any impact. Additionally, attenuation, highlight angle, and shadow attributes don’t apply to ambient lights.
  • omni gentle is an omnidirectional gentle supply. As a result of an omnidirectional gentle casts equal illumination in all instructions, the orientation of the node containing the sunshine has no impact. Highlight angle and shadow attributes don’t apply to directional lights.
  • directional gentle illuminates the scene with fixed route and depth. The place of the node containing this gentle has no impact on the scene. Attenuation and highlight angle attributes don’t apply to directional lights.
  • spot gentle illuminates a cone-shaped space. The place and orientation of the node containing the sunshine determines the world lit by the highlight, and all lighting attributes have an effect on its look.
  • IES (Illumination Engineering Society) gentle illuminates the scene with form, route and depth of illumination laid out in a IES normal file. This file format was created for the digital switch of photometric information over the online. IES gentle recordsdata are created by many main lighting producers and could be downloaded freely from their web sites. SCNLight offers additionally the iesProfileURL property to import the sunshine IES normal file into SceneKit. After setting this property to a URL that references a legitimate IES profile, you could set the sunshine’s kind property to IES to load that file and apply its impact. You possibly can obtain an instance of a lightweight IES file from right here.
  • probe gentle could be use to measure the route and the depth of the sunshine in some extent of the 3D area. They’re native lights going through in the direction of the scene. They seize the native subtle contribution. So when shading some extent on a floor we are able to discover the closest gentle probes and interpolate lighting from these probes. Gentle probes are actually light-weight and environment friendly. Apple recommends so as to add lots of them to the scene.

Relying on the ultimate visible look you wish to present to your scene, you may select a number of gentle supply sorts. To create a lightweight supply, you create an occasion of SCNLight. Then, you specify the kind of gentle and, relying on the kind you select, you may configure completely different properties of the sunshine. Lastly, you may both create a brand new node or use an present node of your scene and connect the sunshine to it. For instance, right here methods to create a highlight supply:

Gentle probes

A selected consideration is required for gentle probes. As mentioned above, a lightweight probe is a form of device you should utilize to measure the sunshine of your scene. Why do wish to try this? Nicely, when simulating the sunshine in a scene could be very troublesome to estimate the sunshine if there may be an object between your nodes and the sunshine supply. This object could be there as a result of is a part of the surroundings.

In a future put up, we are going to speak about Bodily-Primarily based Rendering (PBR) strategies. Right here, I simply wish to point out that there’s a option to render a scene in order that it appears actual. That is completed utilizing photorealistic rendering. Gentle probes are essential on this case, as a result of the might help the simulation to compute ambient occlusions.

Working with lights

When you create a lightweight and specify its kind, you may set and modify completely different gentle options relying on the chosen gentle kind. Options reminiscent of the sunshine attenuation (attenuationStartDistance, attenuationEndDistance, attenuationFalloffExponent), colour (colour), temperature and depth provide you with a strong management of the lights.

Shadows

Gentle objects are accountable for shadows. If you wish to render shadows in your scene, that you must set the castsShadow property to true (by default this property is about to false). The property shadowColor permits to manage the colour of the shadow. The default worth is black with 50% opacity. shadowRadius is a CGFloat specifying the quantity of blur across the edges of shadows. The shadowMapSize property represents the dimensions of the 2D shadow map generated by SceneKit. Setting this worth to CGSize.zero makes SceneKit select the dimensions robotically. Take into account that a big shadow map measurement implies larger rendering prices.
The shadowMode property could be set to ahead (default worth), deferred or modulated. The primary worth makes SceneKit render the shadow when rendering the scene. Deferred mode implies that SceneKit renders shadows in a put up processing go. The third mode (modulated) refers back to the gobo property. A gobo (also called a flag or cookie) is a stencil, gel, or different object positioned simply in entrance of a lightweight supply, shaping or coloring the beam of sunshine. The gobo property is an SCNMaterialProperty kind. The gobo property applies solely to lights whose kind property is spot.

Shadows instance

Final time, we created a quite simple scene with a sphere. Let’s use this scene so as to add a lightweight and shadows.

Create a brand new Xcode challenge and select a single-view utility template. Add a brand new Scene and create a brand new scene.scnassets folder as I confirmed you final time. Add a SCNView to the view controller principal view (don’t neglect so as to add constraints). Edit the ViewController.swift file within the following manner:

Let’s open the scene file. Add to the scene file a sphere at place [0, 1, 0]. Add additionally a flooring object to the scene. Then, change the digicam place to [0, 5, 6] and its Euler angles to [–45, 0, 0]. Lastly, add a directional gentle to the scene and alter its Euler angles to [–30, 0, 0].

Let’s now add the shadows. Choose the directional gentle and Attributes Inspector. Within the Shadow part, verify the Casts Shadows flag and you might be completed. From the attribute inspector you may change many (and extra) parameters I highlighted above. You possibly can obtain this easy challenge from right here.

Attempt to add extra objects to the scene and alter the sunshine attributes.

On this put up, we analyzed methods to have an effect on the visible look of a SceneKit scene. We lined ideas reminiscent of lights and shadows. We additionally gave a take a look at the geometry of a node. Placing collectively these new ideas, and people highlights within the earlier put up, now you can begin to construct your lifelike 3D scenes.
Subsequent time we’re going to take a look at the supplies one other vital element that can make your scene trying lifelike.

Geppy

Geppy Parziale (@geppyp) is cofounder of InvasiveCode. He has developed many iOS purposes and taught iOS improvement to many engineers around the globe since 2008. He labored at Apple as iOS and OS X Engineer within the Core Recognition workforce. He has developed a number of iOS and OS X apps and frameworks for Apple, and lots of of his improvement tasks are top-grossing iOS apps which might be featured within the App Retailer. Geppy is an knowledgeable in laptop imaginative and prescient and machine studying.

iOS Consulting | INVASIVECODE

iOS Training | INVASIVECODE

(Visited 5,099 instances, 3 visits immediately)





Source_link

Leave a Reply

Your email address will not be published.