ferram4 / Ferram-Aerospace-Research

Aerodynamics model for Kerbal Space Program
Other
239 stars 131 forks source link

fixed issues with Unity API used outside of the main thread #129

Closed neuoy closed 8 years ago

neuoy commented 8 years ago

In order to debug code with the procedure described here, the code must not access Unity API from a thread that is not the main one. Since FAR uses multithreading for high performance voxelization, it throws several exceptions when running in such an environment, and doesn't actually produce any drag or lift.

I've updated the code to make it work correctly. Most cases were just about the overloaded == operator, but some parts are now delegated to the main thread (checking object existence, etc.), which could have a negative impact on performances (it makes the voxelization thread wait until the next main thread update). Which is why I detect at startup wether it's a vanilla Unity or the KSP version that runs, and choose the appropriate execution path, so that performance drop, if any, would be only for modders that want debugging tools.

Since this work can help other modders (both those that work on FAR, maybe including yourself, and those that work on another mod that depends on FAR), I wanted to share it, but I'd understand if you don't want the added code complexity.

ferram4 commented 8 years ago

Sure, it makes sense. I tell ya what, here's what we're gonna do with this: I'm not gonna merge this until the 1.1 beta is out and I can make FAR compatible with that. Once that's done we can look into merging this and any other changes that might be needed after the update.

neuoy commented 8 years ago

OK. In the meantime, I'll double check the null comparisons I've replaced, because after reading Unity doc, the overloaded == operator is checking if the object has been destroyed even if the C# instance is still there, so I can't just replace them by reference comparisons. This also makes me wonder if you ever got NullReferenceException due to race conditions (you check for null in a thread, but if for example a Part is destroyed right after that, you'll still try to access it from the thread)?

ferram4 commented 8 years ago

Alright, so what I have working right now is on the KSP_update branch, if you wanna mess with it.

I haven't gotten any NREs from race conditions that I've noticed.

neuoy commented 8 years ago

Thanks for the merge :) And sorry I didn't take the time to further test it as I said.

ferram4 commented 8 years ago

Np, feel free to keep checking to make sure this works.