Exemplo n.º 1
0
        // https://raytracing.github.io/books/RayTracingTheNextWeek.html#boundingvolumehierarchies
        public BvhNode(List <IHittable> srcObjects, int start, int end, AbstractSampler <int> sampler = null)
        {
            sampler ??= new ThreadSafeSampler <int>(count => IntSampling.Random(count, 0, 3), SAMPLES);

            var objects = srcObjects;
            int axis    = sampler.GetSample();

            int Comparator(IHittable a, IHittable b) => BoxCompare(a, b, axis);

            int objectSpan = end - start;

            switch (objectSpan)
            {
            case 1:
                _left = _right = objects[start];
                break;

            case 2 when Comparator(objects[start], objects[start + 1]) < 0:
                _left = objects[start];

                _right = objects[start + 1];
                break;

            case 2:
                _left  = objects[start + 1];
                _right = objects[start];
                break;

            default:
                objects.Sort(start, objectSpan - 1, new FuncComparer <IHittable>(Comparator));
                int mid = start + objectSpan / 2;
                _left  = new BvhNode(objects, start, mid, sampler);
                _right = new BvhNode(objects, mid, end, sampler);
                break;
            }

            var boxLeft  = _left.BoundingBox();
            var boxRight = _right.BoundingBox();

            _box = boxLeft + boxRight;
        }