Skip to content

Instantly share code, notes, and snippets.

@hecomi
Created November 9, 2016 14:03
Show Gist options
  • Save hecomi/7a906c741974c7de991484b4d070d041 to your computer and use it in GitHub Desktop.
Save hecomi/7a906c741974c7de991484b4d070d041 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Threading;
using UnityEngine;
using Windows.Kinect;
public class DepthParticle : MonoBehaviour
{
public MultiSourceManager multiSouceManager;
public ParticleSystem particleSystem;
public Color particleColor = new Color(0f, 1f, 0f, 1f);
public float particleSize = 10f;
public int shrink = 10;
public float scale = 2f;
private int width_, height_;
private KinectSensor kinect_;
private CameraSpacePoint[] cameraSpacePoints_;
private ParticleSystem.Particle[] particles_;
private Thread depthImageToParticleThread_;
private bool isUpdateParticles = true;
void Start()
{
kinect_ = KinectSensor.GetDefault();
var frameDescription = kinect_.DepthFrameSource.FrameDescription;
width_ = frameDescription.Width;
height_ = frameDescription.Height;
var size = width_ * height_;
cameraSpacePoints_ = new CameraSpacePoint[size];
particles_ = new ParticleSystem.Particle[size / shrink];
depthImageToParticleThread_ = new Thread(DepthImageToParticleThreadFunc);
depthImageToParticleThread_.Start();
}
void Update()
{
particleSystem.SetParticles(particles_, particles_.Length);
particleSystem.startLifetime = 1f;
if (Input.anyKeyDown) {
isUpdateParticles ^= true;
}
}
void OnApplicationQuit()
{
if (depthImageToParticleThread_.IsAlive) {
depthImageToParticleThread_.Abort();
}
}
void DepthImageToParticleThreadFunc()
{
try {
_DepthImageToParticleThreadFunc();
} catch (Exception e) {
if (!(e is ThreadAbortException)) {
Debug.LogError("Unexpected Death: " + e.ToString());
}
}
}
void _DepthImageToParticleThreadFunc()
{
for (;;) {
Thread.Sleep(0);
if (!kinect_.IsAvailable || !isUpdateParticles) continue;
var raw = multiSouceManager.GetDepthData();
var color = multiSouceManager.GetColorData();
if (raw == null) continue;
kinect_.CoordinateMapper.MapDepthFrameToCameraSpace(raw, cameraSpacePoints_);
for (int i = 0, n = 0; i < particles_.Length && n < cameraSpacePoints_.Length; ++i, n += shrink) {
if (raw[i] == 0) {
particles_[i].position = Vector3.zero;
particles_[i].color = Color.clear;
particles_[i].size = 0;
particles_[i].lifetime = -1f;
} else {
var p = cameraSpacePoints_[n];
particles_[i].position = new Vector3(p.X, p.Y, p.Z) * scale;
particles_[i].color = particleColor;
particles_[i].size = particleSize;
particles_[i].lifetime = 1f;
particles_[i].velocity = Vector3.one;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment