private IFNChargedParticleSource FindChargedParticleSource(Part currentpart, int stackdepth, int parentdepth)
        {
            if (currentpart == null)
            {
                return(null);
            }

            if (stackdepth == 0)
            {
                return(currentpart.FindModulesImplementing <IFNChargedParticleSource>().FirstOrDefault());
            }

            foreach (var attachNodes in currentpart.attachNodes.Where(atn => atn.attachedPart != null))
            {
                IFNChargedParticleSource particleSource = FindChargedParticleSource(attachNodes.attachedPart, (stackdepth - 1), parentdepth);

                if (particleSource != null)
                {
                    return(particleSource);
                }
            }

            if (parentdepth > 0)
            {
                IFNChargedParticleSource particleSource = FindChargedParticleSource(currentpart.parent, (stackdepth - 1), (parentdepth - 1));

                if (particleSource != null)
                {
                    return(particleSource);
                }
            }

            return(null);
        }
        private IFNChargedParticleSource BreadthFirstSearchForChargedParticleSource(int stackdepth, int parentdepth)
        {
            for (int currentDepth = 0; currentDepth <= stackdepth; currentDepth++)
            {
                IFNChargedParticleSource particleSource = FindChargedParticleSource(part, currentDepth, parentdepth);

                if (particleSource != null)
                {
                    _attached_reactor_distance = currentDepth;
                    return(particleSource);
                }
            }
            return(null);
        }
        private void ConnectToReactor()
        {
            // first try to look in part
            _attached_reactor = this.part.FindModuleImplementing <IFNChargedParticleSource>();

            // try to find nearest
            if (_attached_reactor == null)
            {
                _attached_reactor = BreadthFirstSearchForChargedParticleSource(10, 1);
            }

            if (_attached_reactor != null)
            {
                _attached_reactor.ConnectWithEngine(this);
            }
        }