Fixing or avoiding memory leak in default third party library - ios

I developed an app that includes the ability to preview the subdivision results of a 3D model on the fly. I have my own catmull clark subdivision functions to permanently modify the geometry, but I use the .subdivisionLevel property of the SCNGeometry to temporarily subdivide the model as a preview. In most cases previewing does not automatically mean the user will go for the permanent option.
.subdivisionLevel uses (just as MDLMesh’s subdivision, which I tried as a workaround) Pixar’s OpenSubdiv to do the actual subdivision and smoothing. It works faster than my own but more importantly it doesn’t permanently modify the vertex data I provide through a SCNGeometry source.
The problem is, I can’t get it to stop leaking memory. I first noticed this a long time ago, figured it was something in my code. I don’t think it’s just one specific IOS version and it happens in both Swift and Objective C. Eventually I set up a small example adding just 1 line to the SceneKit game template in Xcode, setting the ship’s subdivisionLevel to 1. Instruments shows that immediately results in memory leaks:
I submitted a bug report to Apple a week ago but I’m not sure I can expect a reply or a fix anytime soon or at all. The screenshot is from a test with a very small model, but even with small models (hundreds to couple of thousand vertices) it leaks a lot and fast and will lead to the app crashing.
To reproduce, create a new project in Xcode based on the SceneKit game template and add the following lines to handletap:
if result.node.geometry!.subdivisionLevel == 3 {
result.node.geometry!.subdivisionLevel = 0
} else {
result.node.geometry!.subdivisionLevel = 3
}
(Remove the ! For objective c)
Tap the ship to leak megabytes, tap it some more and it quickly adds up.
OpenSubdiv is used in 3D Studio max as well as others obviously and it appears to be in Apple’s implementation. So my question is: is there a way to fix/avoid this problem without giving up on the subdivision features of SceneKit entirely, or is a response from Apple my only chance?

Going through the WWDC videos to get an idea of how committed Apple is to OpenSubdiv and thus the chance of them fixing the leaks, I found the subdivision can be performed on the GPU by Metal since the latest SceneKit update.
Here are the required two lines (Swift) if you want to use subdivision in SceneKit or Model IO:
let tess = SCNGeometryTessellator()
geometry.tessellator = tess
(from WWDC 2017 What's new in Scenekit, 23:45 into the video)
This will cause the subdivision to be performed on the GPU (thus faster, especially at higher levels), use less memory, and most importantly, releases the memory when setting the subdivision level lower or back to zero.

Related

SceneKit objects not showing up in ARSCNView about 1 out of 100 times

I can't share much code because it's proprietary, but this is a bug that's been haunting me for awhile. We have SceneKit geometry added to the ARKit face node and displayed inside an ARSCNView. It works perfectly almost all of the time, but about 1 in 100 times, nothing shows up at all. The ARSession is running, and none of the parent nodes are set to hidden. Further, when I look at Debug Memory Graph function in Xcode, the geometry appears to be entirely visible there (and doesn't seem to be set to hidden). I can see all the nodes attached to the face node perfectly within the ARSCNView of the memory graph, but on the screen, nothing shows up. This has been an issue for multiple iOS versions, so it didn't just appear with a recent update.
Has anybody run into a similar problem, or does anybody have any ideas to look into? Is it an apple bug, or is there a timing issue I might not be aware of? It's been really hard to debug because of how infrequent it is, and I haven't found it discussed on any other forums (but point me in the right direction if there is a previous discussion). Thanks!
This is pretty common practice if AR tracking is poor for some reason.
I ran into a similar problem too. I think it's definitely a tracking error which arises due to the fault of the user of AR app. Sometimes, if you're using World Tracking Config in ARKit and track a surrounding environment offhandedly or if you are tracking under inappropriate conditions – you get a sloppy tracking data which results in situation when your World Grid/Axis may be unpredictably shifted aside and your model may fly away somewhere. If such a situation arises - look for your model somewhere nearby – maybe it’s behind you.
If you're using a gadget with a LiDAR, the aforementioned situation is almost impossible, but if you're using a gadget with no LiDAR you need thoroughly track your room. Also there must be good lighting conditions and high-contrast real-world objects with distinguishable non-repetitive textures.

FPS drop when adding child to a scene ARKit/SceneKit

I'm working on an ARKit project for 4 months now.
I noticed that when adding a child to my scene rootNode, there is a FPS drop. The device freezes for less than a second.
I did a lot of research and trials, noticed that all Apple's code examples have this FPS drop too when placing an object.
It does not matter if the node is added directly (scene.rootNode.addChild(child)) or if it's added in the renderer loop at different phases (didUpdateAtTime, didApplyAnimations etc...).
I found that once an object has been added to a scene, the next added object will render immediately. I use a 3D model created in SceneKit editor, clone it to generate my different nodes before adding them as child. I do this loading work before placing the objects.
Instruments shows that the renderer loop is busy for the duration of the freeze.
The only solution that I found is to add my nodes to the scene behind a loading screen before starting the whole experience.
Is that a normal behavior in game programming to render nodes before using them ?
Thanks guys
With the release of ARKit 3.0 and its satellite – RealityKit (framework with optimised rendering engine and changed scene's hierarchy, that was written in Swift hence it has no Objective-C binding), a drop-frame, when adding a child, is reduced to an imperceptible value.
And such a predictable behaviour of ARKit3/RealityKit ligament is especially true for devices with processors A12 Bionic and A13 Bionic manufactured on 7 nm process (and, of course, due to the fact they have last-gen neural engines and powerful GPUs).
For devices with a less powerful processors (A9, A10, A11), it is advisable to use 3D models with a total number of polygons of no more than 10K per model, and with usual shaders like .blinn or .phong (not PBR).
I believe it's quite a common practice for games and apps that use game engines, to firstly load (or cache) all the necessary game assets (like 3D models, textures, sound files, etc) into RAM before using them. For further details please read this article and this article.
However, it’s worth saying that AR games, unlike VR games, consume considerably more processing power, therefore they need to be carefully optimised. So, you're absolutely right, rendering nodes before using them and it's a normal behaviour in game programming.

SKView in UICollectionView terrible performance

Adding empty SKView to UICollectionView cell makes the scrolling almost impossible on iPhone 6 (iOS 9.x). Lets say collection view contains 6 items of which first 3 are visible, scrolling horizontally for next 3 items takes 3sec with jerkiness.
Here's the relating part of code:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ACDFilterCollectionViewCellConstants.CellIdentifier, forIndexPath: indexPath) as! ACDFilterCollectionViewCell
let filterType = filters[indexPath.row]
cell.titleLabel.text = filterType.rawValue
let skview = SKView(frame: cell.frame)
cell.filterView.addSubview(skview)
return cell
}
What should I do to have a smooth scrolling with SKViews inside my UICollectionViewCells?
On iOS 8.x I'm getting the exception on rendering this view:
I don't know what the specific answer is w.r.t. the cause of the poor performance, but I can give you some pointers as to how to proceed.
The first thing to do is to profile the code. Use Instruments to figure out where the app is spending the most time when you start scrolling. Is setting up the SKViews as they come onto the screen the expensive part? Or is it drawing all those sprite views over and over? Is it something in the sprite views that's taking a long time to draw? I hear that SKShapeNode can be a drag on performance. What happens if you remove all the subnodes from the SKViews?
Once you know where the bottleneck is, you can decide how to proceed. From your comment it sounds like you're only using SKView to render some paths, and maybe you don't need those to animate once they're drawn? If so, perhaps you can use a single offscreen SKView to render your path into an image, and then insert that image into the collection cell. People use collections full of images all the time, and they scroll beautifully.
My initial suggestion would be simply this: Scale back your expectations of what's possible in terms of framework interactions and relationship building between them.
Look into CAShapeLayer and see if it can do enough of what you're attempting to do with SKShapeNode and shaders. There is a "shouldRasterize" feature of of CAShapeLayers, and you can then apply things like Core Image filters, which might get you close to the desired result without using SKViews, SKShapeNode and SKShaders.
The problem you're up against is artificially inflated expectations of quality and performance within Apple's newer APIs and Frameworks, and their ability to interact and contain one another.
This is not your fault.
Apple has mastered the art of Showmanship and Salesmanship, long ago.
For a very long time these arts were reserved for physical product releases - the pitching and promoting of the devices people buy.
Sometime around the ailing and death of the late great Mr Jobs (may he RIP) there was a transition underway to promote far more actively the rapid development and early release of software to the App Store.
Most of this was part of the war on Android and Google. There must have been some consensus (probably amongst the supplier focused channels of the company that now lead) that getting as many apps into the store as possible was a way to nullify and/or beat Android.
To this end iOS 7 was created, UICollectionViews, AutoLayout and all manner of other "wonderful" goodies designed to remove the need (and concern) for design and designers for most app creation.
These facilities give the impression that anything and everything can be done with APIs, and that there's little to no need to consider design, nor even technical design.
So Developers plod into the frameworks, bright eyed, bushy tailed, and optimistic about their chances or realising anything they conceive... if they simply use a blend of the frameworks and APIs available to them, via the relationships they perceive to exist between frameworks from their understanding of the WWDC videos and other Apple promotional materials.
Unfortunately the aforementioned salesmanship and showmanship means that what you perceive to be possible is actually limited to the literal demonstrations you're shown. The inferred and suggested possible potential of the frameworks for interwoven relationships and success are just that... POSSIBLE POTENTIAL future functionality.
Most everything other than what is literally demonstrated is broken, or in some other way massively constrained and ill-performing. In some cases that which is demonstrated is also subsequently broken or doesn't make it to the release.
So if you're taking the time to imagine something like combining SKViews within UICollectionViews, and that this relationship should work, that assumption is your problem.
This gets far worse when you start thinking about SKShapeNodes and Shaders, both of which have known issues within SceneKit. Obviously you've found that the issue is that SKViews inside UICollectionViews aren't performant. That is the first problem. You're going to have far more problems gleaning performance from SKShapeNodes and your shaders later, and then the issue of immutability of the SKShapeNode is going to crop up for your animations, too.
It's not an incorrect assumption, you've been lead to believe this modularity of frameworks is a thing, and a huge feature of the massive frameworks of iOS.
However it's all early days, and that's not mentioned. Sprite Kit is fundamentally broken in iOS 9, you can read more about many of its problems here:
https://forums.developer.apple.com/thread/14487
here:
https://forums.developer.apple.com/thread/20758
here:
https://forums.developer.apple.com/thread/17463
There has been no formal communication about the cause and/or nature of the issues blighting those using Scene Kit in iOS 9 that I'm aware of, despite the noise about its many issues.
One enormous issue that's plagued many is that any use of UIKit and SKViews (in either way they can inter-relate) causes huge performance problems in iOS 9. At this point there are no apparent ways around this problem other than keeping these two frameworks separate.
One big change on iOS 9 vs. iOS 8 is the switch from OpenGL to Metal for SpriteKit and SceneKit. I suggest you try overriding that default, and switch back to OpenGL, by adding the key/value pair PrefersOpenGL/YES to your Info.plist. See Technical Q&A QA1904, Specifying the renderer for SpriteKit and SceneKit.

iOS MapKit Performance Issue Using Satellite Tiles

I have an iOS 8 app that uses MapKit. I recently discovered a performance problem with the app when running a video decompression in addition to displaying a map. The app was unable to keep up with the flow of incoming data when using the satellite view tile set. However, this problem vanished the moment I swapped to the default MapKit tile set. The app is not CPU bottlenecked when the problem is occurring. It makes sense to me that the default (vector) map tile set is easier to display, but I am confused about why the issue is happening in the first place.
The problem seems strange to me because there is no movement or manipulation of the map when the problem is occurring. I would understand the issue better if it happened when manipulating the map in addition to rendering video to the screen, but the problem exists even with no user input. I am constrained in analyzing the system because we use a hardware accessory, so some Instruments are not available over wireless performance analysis. I am not using a high number of annotations, overlays, or other objects. We have a few custom annotations and overlays in use. There are existing apps that do this exact combination of decoding and maps, without the performance problem, so I suspect it's a configuration issue.
Are there certain attributes on the MKMapView that I can set to improve performance? I am at a loss as to what to investigate further since I cannot make the problem happen with the GPU Instrument active and the CPU doesn't appear to be the constraint.

Is iOS glGenerateMipmap synchronous, or is it possibly asynchronous?

I'm developing an iPad app that uses large textures in OpenGL ES. When the scene first loads I get a large black artifact on the ceiling for a few frames, as seen in the picture below. It's as if higher levels of the mipmap have not yet been filled in. On subsequent frames, the ceiling displays correctly.
This problem only began showing up when I started using mipmapping. One possible explanation is that the glGenerateMipmap() call does its work asynchronously, spawning some mipmap creation worker (in a separate process, or perhaps in the GPU) and returning.
Is this possible, or am I barking up the wrong tree?
Within a single context, all operations will appear to execute strictly in order. However, in your most recent reply, you mentioned using a second thread. To do that, you must have created a second shared context: it is always illegal to re-enter an OpenGL context. If already using a shared context, there are still some synchronization rules you must follow, documented at http://developer.apple.com/library/ios/ipad/#DOCUMENTATION/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithOpenGLESContexts/WorkingwithOpenGLESContexts.html
It should be synchronous; OpenGL does not in itself have any real concept of threading (excepting the implicit asynchronous dialogue between CPU and GPU).
A good way to diagnose would be to switch to GL_LINEAR_MIPMAP_LINEAR. If it's genuinely a problem with lower resolution mip maps not arriving until later then you'll see the troublesome areas on the ceiling blend into one another rather than the current black-or-correct effect.
A second guess, based on the output, would be some sort of depth buffer clearing issue.
I followed #Tommy's suggestion and switched to GL_LINEAR_MIPMAP_LINEAR. Now the black-or-correct effect changed to a fade between correct and black.
I guess that although we all know that OpenGL is a pipeline (and therefore asynchronous unless you are retrieving state or explicity synchronizing), we tend to forget it. I certainly did in this case, where I was not drawing, but loading and setting up textures.
Once I confirmed the nature of the problem, I added a glFinish() after loading all my textures, and the problem went away. (Btw, my draw loop is in the foreground and my texture loading loop - because it is so time consuming and would impair interactivity - is in the background. Also, since this may vary between platforms, I'm using iOS5 on an iPad 2)

Resources