Beispiel #1
0
        public void Submit(SampleBuffer samples)
        {
            if (samples.Frames == 0)
            {
                return;
            }

            if (_replayGainExport != null)
            {
                samples = _replayGainExport.Value.Process(samples);
            }

            if (samples.IsInterleaved)
            {
                Span <float> interleavedSamples = stackalloc float[samples.Frames * samples.Channels];
                samples.CopyToInterleaved(interleavedSamples);
                _encoder !.EncodeInterleaved(interleavedSamples, samples.Frames);
            }
            else if (samples.Channels == 1)
            {
                Span <float> monoSamples = stackalloc float[samples.Frames];
                samples.CopyTo(monoSamples);
                _encoder !.Encode(monoSamples, null);
            }
            else
            {
                Span <float> leftSamples  = stackalloc float[samples.Frames];
                Span <float> rightSamples = stackalloc float[samples.Frames];
                samples.CopyTo(leftSamples, rightSamples);
                _encoder !.Encode(leftSamples, rightSamples);
            }
        }
Beispiel #2
0
        protected void SamplesCallback(IntPtr sampleBuffer, int size)
        {
            if (size == 0)
            {
                return;
            }

            if (size > 2048)
            {
                Debug.LogError("Input buffer is larger than target size!");
            }

            SampleBuffer buffer = GetEmptyBuffer();

            //Copy samples into empty buffer.
            Marshal.Copy(sampleBuffer, buffer.GetBuffer(), 0, size);

            //Set buffer to in use.
            buffer.Consume(0, size);

            //Link the buffer.
            if (this.HeadBuffer == null)
            {
                this.HeadBuffer = buffer;
            }
            else
            {
                this.HeadBuffer.Next = buffer;
                buffer.Previous      = this.HeadBuffer;
                this.HeadBuffer      = buffer;
            }
        }
        protected void Init(IIntersectionEngine device, bool lowLatency, IImageFilm pixelDevice, ISampler sampler,
                            SurfaceSampler ss)
        {
            this.intersectionDevice = device;
            // Sample buffer
            var sampleBufferSize = lowLatency ? (this.SAMPLE_BUFFER_SIZE / 4) : this.SAMPLE_BUFFER_SIZE;
            this.sampleBuffer = new SampleBuffer(sampleBufferSize);

            this.width = sampler.Width;
            this.height = sampler.Height;
            var rayBufferSize = lowLatency ? (RayBuffer.RayBufferSize / 8) : RayBuffer.RayBufferSize;
            this.sampler = sampler;
            this._pathRayProcessors = new PathBufferBase[DeviceRenderBufferCount];
            this.rayBuffers = new RayBuffer[DeviceRenderBufferCount];
            this.pixelDevice = pixelDevice;
            for (int i = 0; i < DeviceRenderBufferCount; i++)
            {
                this.rayBuffers[i] = new RayBuffer(rayBufferSize);
                this.rayBuffers[i].UserData = this.threadIndex;

                this._pathRayProcessors[i] = this.CreatePathBuffer(this.scene.MaxPaths, this.scene, pixelDevice, sampler, ss);
                this._pathRayProcessors[i].ThreadId = this.threadIndex;
            }

            this.renderThread = null;
        }
Beispiel #4
0
        public StreamedAudioPlayer(UInt32 id, string name, string path, int referenceLength)
        {
            this.path            = path;
            this.referenceLength = referenceLength;
            this.decoder         = new AudioDecoder(id, name, 4096, new FileStreamProvider(path), SamplesCallback);

            this.channelCount = decoder.GetChannelCount();
            this.sampleRate   = decoder.GetSampleRate();

            //No need to factor in channels in this length, already taken care of.
            this.samplesLength = decoder.GetSamplesLength();

            //Half a second is what we want.
            this.cacheSize = this.sampleRate / this.channelCount;

            //Create an empty bufferpool. We populate it later.
            int poolSize = this.cacheSize / BUFFER_SIZE;

            this.bufferPool = new Stack <SampleBuffer>(this.cacheSize / BUFFER_SIZE);
            for (int i = 0; i < poolSize; i++)
            {
                SampleBuffer buffer = new SampleBuffer(BUFFER_SIZE, i);
                bufferPool.Push(buffer);
            }

            this.clip           = AudioClip.Create(decoder.GetName(), samplesLength, channelCount, sampleRate, true, OnAudioRead, OnAudioSetPosition);
            this.beginStreaming = false;
        }
Beispiel #5
0
        public override void Splat(SampleBuffer sampleBuffer)
        {

            var waveLengthWeight = 1f/(SpectralSamplingHelper.SpectralSamples);
            lambdas[lambdaSample]=(HeroWavelength);
            wls[lambdaSample] = (waveRadiance)* waveLengthWeight;

            lambdaSample++;
            if (lambdaSample >= SpectralSamplingHelper.SpectralSamples)
            {
                var lb = lambdas.ToList();
                lb.Sort();
                lambdas = lb.ToArray();
                var spd = new IrregularSPD(lambdas, wls, SpectralSamplingHelper.SpectralSamples, SpectralSamplingHelper.SpectralResolution, SPDResamplingMethod.Linear);
                //var spd = new RegularSPD(wls, SampledSpectrum.sampledLambdaStart,SampledSpectrum.sampledLambdaEnd, WaveLengthSampler.SpectralSamples);

                var pix = 
                    //ColorFactory.ToRgb(spd);
                    spd.ToRgb();
                  
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref pix);
                lambdaSample = 0;
            }
            this.InitPath(pathIntegrator);
        }
        protected void Init(IIntersectionEngine device, bool lowLatency, ImageFilmBase pixelDevice, IPrimarySpaceSampler sampler,
                          SurfaceSampler ss)
        {
            intersectionDevice = device;
            // Sample buffer
            var sampleBufferSize = lowLatency ? (SAMPLE_BUFFER_SIZE / 4) : SAMPLE_BUFFER_SIZE;
            sampleBuffer = new SampleBuffer(sampleBufferSize);

            width = sampler.Width;
            height = sampler.Height;
            var rayBufferSize = lowLatency ? (RayBuffer.RayBufferSize / 8) : RayBuffer.RayBufferSize;
            this.sampler = sampler;
            _pathRayProcessors = new PathIntegrator[DeviceRenderBufferCount];
            rayBuffers = new RayBuffer[DeviceRenderBufferCount];

            for (int i = 0; i < DeviceRenderBufferCount; i++)
            {
                rayBuffers[i] = new RayBuffer(rayBufferSize);
                rayBuffers[i].UserData = threadIndex;

                _pathRayProcessors[i] = this.CreatePathBuffer(scene.MaxPaths, scene, pixelDevice, sampler, ss);
            }

            renderThread = null;
        }
Beispiel #7
0
            internal void Init(LabelValues labelValues, SummaryConfiguration configuration, DateTime now)
            {
                base.Init(labelValues, configuration);

                _sortedObjectives  = new double[Configuration.Objectives.Count];
                _buffer            = new SampleBuffer(Configuration.BufCap);
                _streamDuration    = new TimeSpan(Configuration.MaxAge.Ticks / Configuration.AgeBuckets);
                _headStreamExpTime = now.Add(_streamDuration);
                _bufferExpTime     = _headStreamExpTime;

                _streams = new QuantileStream[Configuration.AgeBuckets];
                for (int i = 0; i < Configuration.AgeBuckets; i++)
                {
                    _streams[i] = QuantileStream.NewTargeted(Configuration.Objectives);
                }

                _headStream = _streams[0];

                for (int i = 0; i < Configuration.Objectives.Count; i++)
                {
                    _sortedObjectives[i] = Configuration.Objectives[i].Quantile;
                }

                Array.Sort(_sortedObjectives);
            }
Beispiel #8
0
        protected override unsafe DecoderWriteStatus WriteCallback(IntPtr handle, ref Frame frame, IntPtr buffer,
                                                                   IntPtr userData)
        {
            if (frame.Header.Channels == 1)
            {
                Samples = new SampleBuffer(
                    new Span <int>(
                        Marshal.ReadIntPtr(buffer).ToPointer(),
                        (int)frame.Header.BlockSize),
                    (int)frame.Header.BitsPerSample);
            }
            else
            {
                Samples = new SampleBuffer(
                    new Span <int>(
                        Marshal.ReadIntPtr(buffer).ToPointer(),
                        (int)frame.Header.BlockSize),
                    new Span <int>(
                        Marshal.ReadIntPtr(buffer, IntPtr.Size).ToPointer(),
                        (int)frame.Header.BlockSize),
                    (int)frame.Header.BitsPerSample);
            }

            return(DecoderWriteStatus.Continue);
        }
Beispiel #9
0
        public unsafe void Submit(SampleBuffer samples)
        {
            if (samples.Frames == 0)
            {
                return;
            }

            Span <int> buffer = stackalloc int[samples.Frames * samples.Channels];

            samples.CopyToInterleaved(buffer, _bitsPerSample);

            var bufferList = new AudioBufferList
            {
                NumberBuffers = 1,
                Buffers       = new AudioBuffer[1]
            };

            bufferList.Buffers[0].NumberChannels = (uint)samples.Channels;
            bufferList.Buffers[0].DataByteSize   = (uint)(buffer.Length * sizeof(int));
            bufferList.Buffers[0].Data           = new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)));

            var status = _audioFile !.Write(bufferList, (uint)samples.Frames);

            if (status != ExtendedAudioFileStatus.Ok)
            {
                throw new AudioEncodingException($"Apple Lossless encoder encountered error '{status}'.");
            }
        }
        private void FilterFirstTrackInLibrary(SampleType dataPathSampleType, SampleType outputSampleType, string configFilePath)
        {
            CrossTimeEngine dspEngine = new CrossTimeEngine(configFilePath, this);

            string musicFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            string firstArtistPath = Directory.GetDirectories(musicFolderPath).First();
            string firstAlbumPath  = Directory.GetDirectories(firstArtistPath).First();
            string firstTrackPath  = Directory.GetFiles(firstAlbumPath, "*.flac").First();

            this.TestContext.WriteLine("Load and buffer");
            DateTime loadStartedUtc           = DateTime.UtcNow;
            MediaFoundationReader inputStream = new MediaFoundationReader(firstTrackPath);

            using (SampleBuffer inputBuffer = new SampleBuffer(inputStream))
            {
                DateTime loadStoppedUtc = DateTime.UtcNow;
                this.TestContext.WriteLine("{0}", (loadStoppedUtc - loadStartedUtc).ToString(Constant.ElapsedTimeFormat));

                this.TestContext.WriteLine("Warmup iterations");
                for (int warmup = 0; warmup < 10; ++warmup)
                {
                    this.FilterStream(dspEngine.Configuration, inputBuffer, dataPathSampleType, outputSampleType);
                }

                this.TestContext.WriteLine("Running iterations");
                for (int iteration = 0; iteration < 25; ++iteration)
                {
                    this.FilterStream(dspEngine.Configuration, inputBuffer, dataPathSampleType, outputSampleType);
                }
            }
        }
Beispiel #11
0
    // AudioKernel execution code
    public void Execute(ref ExecuteContext <SVFParameters, SVFProviders> context)
    {
        // Loop through all the active output contexts
        int outputCount = context.Outputs.Count;

        for (int outIdx = 0; outIdx < outputCount; ++outIdx)
        {
            // Get the context output buffer & format
            SampleBuffer outputBuffer = context.Outputs.GetSampleBuffer(outIdx);
            int          channels     = outputBuffer.Channels;
            int          bufferSize   = outputBuffer.Samples;
            int          sampleRate   = context.SampleRate;

            // Get the actual sample buffer
            NativeArray <float> buffer = outputBuffer.Buffer;

            // Get the input buffer
            SampleBuffer        inputBuffer  = context.Inputs.GetSampleBuffer(outIdx);
            NativeArray <float> sourceBuffer = inputBuffer.Buffer;

            // Check if coefficients need to be updated
            double currentQ      = context.Parameters.GetFloat(SVFParameters.Q, 0);
            double currentCutoff = context.Parameters.GetFloat(SVFParameters.Cutoff, 0);
            if (lastQ != currentQ || lastCutoff != currentCutoff)
            {
                CalculateCoefficients(ref context.Parameters, currentQ, currentCutoff, sampleRate);
            }

            // Fill the buffer
            for (int smpIdx = 0; smpIdx < bufferSize; ++smpIdx)
            {
                // Get sample from the inlet
                float sample = sourceBuffer[smpIdx];

                // Calculate bands
                double hpf = alpha0 * (sample - rho * delay[0] - delay[1]);
                double bpf = alpha * hpf + delay[0];
                double lpf = alpha * bpf + delay[1];
                double bsf = hpf + lpf;

                // Cache
                double sn = delay[0];

                // update memory
                delay[0] = alpha * hpf + bpf;
                delay[1] = alpha * bpf + lpf;

                // Apply gain
                currentAmplitude = math.lerp(currentAmplitude, context.Parameters.GetFloat(SVFParameters.Amplitude, smpIdx), 0.01f);
                sample           = ((float)(currentAmplitude * lpf));

                // Copy back
                buffer[smpIdx] = sample;
            }

            // Cache parameters
            lastQ      = currentQ;
            lastCutoff = currentCutoff;
        }
    }
        public override void Splat(SampleBuffer sampleBuffer)
        {

            var waveLengthWeight = 1f/ (SpectralSamplingHelper.SpectralSamples);
            lambdas[lambdaSample] = (HeroWavelength);
            wls[lambdaSample] = (waveRadiance / waveLengthWeight);
            rs += waveRadiance;
            lambdaSample++;
            if (lambdaSample >= SpectralSamplingHelper.SpectralSamples)
            {
                RgbSpectrum pix = RgbSpectrum.ZeroSpectrum();
                if (rs > 0f)
                {
#if RandomWavelength

                var lb = lambdas.ToList();
                lb.Sort();
                lambdas = lb.ToArray();

#endif
                    var spd = new IrregularSPD(lambdas, wls, SpectralSamplingHelper.SpectralSamples, SpectralSamplingHelper.SpectralResolution, SPDResamplingMethod.Linear);      
                    //var spd = new RegularSPD(wls, SampledSpectrum.sampledLambdaStart, SampledSpectrum.sampledLambdaEnd,SpectralSamplingHelper.SpectralSamples);
                    spd.Normalize();
                    pix =
                        //ColorFactory.ToRgb(spd);
                        spd.ToRgb();
                }
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref pix);
                rs = 0;
                lambdaSample = 0;
            }
            this.InitPath(pathIntegrator);
        }
Beispiel #13
0
        internal static void Update(GameTime gt)
        {
            Latency = (float)LatencyTimer.Elapsed.TotalMilliseconds;
            LatencyTimer.Restart();
            Delta = (float)gt.ElapsedGameTime.TotalSeconds;
            if (Math.Abs(Delta) < float.Epsilon)
            {
                Delta = 0.1f;
            }
            CurrentFramesPerSecond = 1.0f / Delta;

            SampleBuffer.Enqueue(CurrentFramesPerSecond);

            if (SampleBuffer.Count > MaximumSamples)
            {
                SampleBuffer.Dequeue();
                AverageFramesPerSecond = SampleBuffer.Average(i => i);
            }
            else
            {
                AverageFramesPerSecond = CurrentFramesPerSecond;
            }

            TotalFrames++;
            TotalSeconds += Delta;
        }
Beispiel #14
0
        protected void BuildInitialBuffer(int size)
        {
            //Buffer initial sampledata.
            decoder.GenerateSampleData();

            //Get tail buffer.
            SampleBuffer currentTail = this.HeadBuffer;

            while (true)
            {
                SampleBuffer previous = currentTail.Previous;

                if (previous == null)
                {
                    break;
                }

                currentTail = currentTail.Previous;
            }

            this.TailBuffer = currentTail;

            //Build initial buffer.
            int currentSize = 0;

            BuildBuffer(this.TailBuffer, size, ref currentSize);
        }
Beispiel #15
0
        void OnAudioSetPosition(int position)
        {
            if (this.HeadBuffer != null)
            {
                SampleBuffer current = this.HeadBuffer;
                while (current != null)
                {
                    SampleBuffer previous = current.Previous;

                    Recycle(current);

                    current = previous;
                }
            }

            this.decoder.SetPosition(position);
            this.HeadBuffer = null;
            this.TailBuffer = null;

            //Set up about half a second of prebuffered sample data.
            BuildInitialBuffer(this.cacheSize);

            //Open up stream buffers for reading.
            BeginStreaming();
        }
Beispiel #16
0
    // AudioKernel execution code
    public void Execute(ref ExecuteContext <VCAParameters, VCAProviders> context)
    {
        // Loop through all the active output contexts
        int outputCount = context.Outputs.Count;

        for (int outIdx = 0; outIdx < outputCount; ++outIdx)
        {
            // Get the context output buffer & format
            SampleBuffer outputBuffer = context.Outputs.GetSampleBuffer(outIdx);
            int          channels     = outputBuffer.Channels;
            int          bufferSize   = outputBuffer.Samples;
            int          sampleRate   = context.SampleRate;

            // Get the actual sample buffer
            NativeArray <float> buffer = outputBuffer.Buffer;

            // Get the input buffer
            SampleBuffer        inputBuffer  = context.Inputs.GetSampleBuffer(outIdx);
            NativeArray <float> sourceBuffer = inputBuffer.Buffer;

            // Fill the buffer
            for (int smpIdx = 0; smpIdx < bufferSize; ++smpIdx)
            {
                // Get sample from the inlet
                float sample = sourceBuffer[smpIdx];

                // Apply amplitude
                currentAmplitude = math.lerp(currentAmplitude, context.Parameters.GetFloat(VCAParameters.Amplitude, smpIdx), 0.01f);
                sample          *= currentAmplitude;

                // Copy back
                buffer[smpIdx] = sample;
            }
        }
    }
        public void Submit(SampleBuffer samples)
        {
            if (samples.Frames == 0)
            {
                return;
            }

#if NETSTANDARD2_0
            var dataSize = samples.Channels * samples.Frames * _bytesPerSample;

            var buffer = ArrayPool <byte> .Shared.Rent(dataSize);

            try
            {
                samples.CopyToInterleaved(buffer, _bitsPerSample);
                // ReSharper disable once PossibleNullReferenceException
                _writer.Write(buffer, 0, dataSize);
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(buffer);
            }
#else
            Span <byte> buffer = stackalloc byte[samples.Channels * samples.Frames * _bytesPerSample];
            samples.CopyToInterleaved(buffer, _bitsPerSample);
            // ReSharper disable once PossibleNullReferenceException
            _writer.Write(buffer);
#endif
        }
    public void Execute(ref ExecuteContext <Parameters, Providers> context)
    {
        if (context.Inputs.Count != 2 || context.Outputs.Count != 1)
        {
            return;
        }

        SampleBuffer voltage       = context.Inputs.GetSampleBuffer(0);
        SampleBuffer input         = context.Inputs.GetSampleBuffer(1);
        SampleBuffer output        = context.Outputs.GetSampleBuffer(0);
        var          voltageBuffer = voltage.Buffer;
        var          inputBuffer   = input.Buffer;
        var          outputBuffer  = output.Buffer;

        int samplesCount  = voltage.Samples;
        int channelsCount = math.min(math.min(voltage.Channels, input.Channels), output.Channels);

        for (int s = 0; s < samplesCount; ++s)
        {
            float multiplier = context.Parameters.GetFloat(Parameters.Multiplier, s);
            for (int c = 0; c < channelsCount; ++c)
            {
                outputBuffer[s * output.Channels + c] = voltageBuffer[s * voltage.Channels + c] * inputBuffer[s * output.Channels + c] * multiplier;
            }
        }
    }
Beispiel #19
0
        public unsafe SampleBuffer DecodeSamples()
        {
            Span <int> buffer = stackalloc int[(int)(_defaultFrameCount * _outputDescription.ChannelsPerFrame)];

            var bufferList = new AudioBufferList
            {
                NumberBuffers = 1,
                Buffers       = new AudioBuffer[1]
            };

            bufferList.Buffers[0].NumberChannels = _outputDescription.ChannelsPerFrame;
            bufferList.Buffers[0].DataByteSize   = (uint)(buffer.Length * Marshal.SizeOf <int>());
            bufferList.Buffers[0].Data           = new IntPtr(Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)));

            var frameCount = _defaultFrameCount;

            // ReSharper disable once PossibleNullReferenceException
            _converter.FillBuffer(ref frameCount, ref bufferList, null);

            if (frameCount == 0)
            {
                Finished = true;
            }

            var result = new SampleBuffer(
                buffer.Slice(0, (int)(frameCount * _outputDescription.ChannelsPerFrame)),
                (int)_outputDescription.ChannelsPerFrame, 32);

            return(result);
        }
        public override void Splat(SampleBuffer sampleBuffer)
        {
#if VERBOSE
            this.pathIntegrator.splattedCount++;
#endif
            this.InitPath(pathIntegrator);
        }
Beispiel #21
0
        public unsafe void Submit(SampleBuffer samples)
        {
            if (samples.Frames == 0)
            {
                return;
            }

            if (_replayGainExport != null)
            {
                samples = _replayGainExport.Value.Process(samples);
            }

            // Request an unmanaged buffer for each channel, then copy the samples to them
            var buffers = new Span <IntPtr>(_encoder !.GetBuffer(samples.Frames).ToPointer(), samples.Channels);

            if (samples.Channels == 1)
            {
                var monoBuffer = new Span <float>(buffers[0].ToPointer(), samples.Frames);
                samples.CopyTo(monoBuffer);
            }
            else
            {
                var leftBuffer  = new Span <float>(buffers[0].ToPointer(), samples.Frames);
                var rightBuffer = new Span <float>(buffers[1].ToPointer(), samples.Frames);
                samples.CopyTo(leftBuffer, rightBuffer);
            }

            WriteFrames(samples.Frames);
        }
Beispiel #22
0
        protected void StreamSampleData(SampleBuffer buffer, ref float[] targetSamples, int offset, int samplesLeft, int cacheSize)
        {
            if (buffer != null)
            {
                bool consumed = buffer.TryConsume(ref targetSamples, ref offset, ref samplesLeft);

                if (consumed)
                {
                    if (System.Object.ReferenceEquals(this.HeadBuffer, this.TailBuffer))
                    {
                        //Debug.LogWarning("Reached Head Buffer");

                        for (int i = offset; i < (offset + samplesLeft); i++)
                        {
                            targetSamples[i] = 0.0f;
                        }
                    }
                    else
                    {
                        this.TailBuffer          = buffer.Next;
                        this.TailBuffer.Previous = null;

                        //Recycle current buffer.
                        Recycle(buffer);

                        //Make sure we always have 44100 samples ahead of playhead in the buffer.
                        int currentSize = 0;
                        BuildBuffer(this.TailBuffer, cacheSize, ref currentSize);

                        StreamSampleData(this.TailBuffer, ref targetSamples, offset, samplesLeft, cacheSize);
                    }
                }
            }
        }
Beispiel #23
0
        public unsafe void Submit(SampleBuffer samples)
        {
            if (samples.Frames == 0)
            {
                return;
            }

            if (_replayGainExport != null)
            {
                samples = _replayGainExport.Value.Process(samples);
            }

            Span <float> buffer = stackalloc float[samples.Frames * samples.Channels];

            samples.CopyToInterleaved(buffer);

            var bufferList = new AudioBufferList
            {
                NumberBuffers = 1,
                Buffers       = new AudioBuffer[1]
            };

            bufferList.Buffers[0].NumberChannels = (uint)samples.Channels;
            bufferList.Buffers[0].DataByteSize   = (uint)(buffer.Length * Marshal.SizeOf <float>());
            bufferList.Buffers[0].Data           = new IntPtr(Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)));

            // ReSharper disable once PossibleNullReferenceException
            var status = _audioFile.Write(bufferList, (uint)samples.Frames);

            if (status != ExtendedAudioFileStatus.Ok)
            {
                throw new AudioEncodingException($"Apple AAC encoder encountered error '{status}'.");
            }
        }
 private void Splat(SampleBuffer smb, float x, float y, ref RgbSpectrum rad)
 {
     if (x < 0 || y < 0)
         return;
     if (x > 1280 || y > 720)
         return;
     smb.SplatSample(x, y, ref rad);
 }
Beispiel #25
0
 public void Reset()
 {
     this.inUse    = false;
     this.start    = 0;
     this.stop     = 0;
     this.position = 0;
     this.Previous = null;
     this.Next     = null;
 }
Beispiel #26
0
        protected void CheckBufferSize(SampleBuffer buffer, ref int currentSize)
        {
            if (buffer != null)
            {
                currentSize += buffer.SamplesAvailible();

                CheckBufferSize(buffer.Next, ref currentSize);
            }
        }
Beispiel #27
0
        protected void Recycle(SampleBuffer buffer)
        {
            buffer.Reset();

            if (this.bufferPool != null)
            {
                this.bufferPool.Push(buffer);
            }
        }
 public PathSampleProcessor(int maxpaths, RayEngineScene rayEngineScene, CorrectorImageFilm pixelDevice, GlobalSamplingContext samplers)
 {
     this.maxPaths = maxpaths;
     this.rayEngineScene = rayEngineScene;
     this.pixelDevice = pixelDevice;
     this.samplers = samplers;
     this.sampleBuffer = pixelDevice.GetFreeSampleBuffer();
     this.paths = new List<PathSampler>(maxPaths);
 }
Beispiel #29
0
        public void CopyToInterleavedIntReturnsExpectedResultsForStereo()
        {
            var outSamples = new int[4];

            using (var samples = new SampleBuffer(new[] { 1, 1 }, new[] { 2, 2 }, 16))
                samples.CopyToInterleaved(outSamples, 16);

            Assert.Equal(new[] { 1, 2, 1, 2 }, outSamples);
        }
 internal virtual void Splat(SampleBuffer buffer)
 {
     if (this.sampleBuffer.IsFull())
     {
         this.statsTotalSampleCount += this.sampleBuffer.GetSampleCount();
         // Splat all samples on the film
         this.film.SplatSampleBuffer(true, sampleBuffer);
         this.sampleBuffer = this.film.GetFreeSampleBuffer();
     }
 }
Beispiel #31
0
        public void IntegersDoNotOverflow()
        {
            var inSamples  = new[] { int.MaxValue, int.MinValue };
            var outSamples = new int[inSamples.Length];

            using (var samples = new SampleBuffer(inSamples, 32))
                samples.CopyToInterleaved(outSamples, 32);

            Assert.True(true);
        }
Beispiel #32
0
        public void CopyToInterleavedPackedReturnsExpectedResultsForInterleaved()
        {
            var inSamples  = new byte[] { 1, 2, 1, 2 };
            var outSamples = new byte[4];

            using (var samples = new SampleBuffer(inSamples, 2, 16))
                samples.CopyToInterleaved(outSamples, 16);

            Assert.Equal(inSamples, outSamples);
        }
Beispiel #33
0
        public void CopyToFloatMonoThrowsExceptionWhenDisposed()
        {
            var samples    = new SampleBuffer(new float[1], 1);
            var outSamples = new float[1];

            samples.Dispose();

            Assert.Throws <ObjectDisposedException>(() =>
                                                    samples.CopyTo(outSamples));
        }
Beispiel #34
0
        public void CopyToInterleavedFloatReturnsExpectedResultsForInterleaved()
        {
            var inSamples  = new[] { 1f, 2f, 1f, 2f };
            var outSamples = new float[4];

            using (var samples = new SampleBuffer(inSamples, 2))
                samples.CopyToInterleaved(outSamples);

            Assert.Equal(inSamples, outSamples);
        }
Beispiel #35
0
        public void CopyToIntStereoThrowsExceptionWhenDisposed()
        {
            var samples         = new SampleBuffer(new float[2], 2);
            var leftOutSamples  = new int[1];
            var rightOutSamples = new int[1];

            samples.Dispose();

            Assert.Throws <ObjectDisposedException>(() => samples.CopyTo(leftOutSamples, rightOutSamples, 16));
        }
Beispiel #36
0
        public void CopyToInterleavedPackedThrowsExceptionWhenDisposed()
        {
            var samples    = new SampleBuffer(new float[2], 2);
            var outSamples = new byte[4];

            samples.Dispose();

            Assert.Throws <ObjectDisposedException>(() =>
                                                    samples.CopyToInterleaved(outSamples, 16));
        }
Beispiel #37
0
        public void CopyToIntStereoReturnsExpectedResultsForStereo()
        {
            var leftOutSamples  = new int[2];
            var rightOutSamples = new int[2];

            using (var samples = new SampleBuffer(new[] { 1, 1 }, new[] { 2, 2 }, 16))
                samples.CopyTo(leftOutSamples, rightOutSamples, 16);

            Assert.All(leftOutSamples, value => Assert.Equal(1, value));
            Assert.All(rightOutSamples, value => Assert.Equal(2, value));
        }
Beispiel #38
0
        /// <summary> Decodes a single frame.
        ///
        /// </summary>
        /// <returns> true if there are no more frames to decode, false otherwise.
        ///
        /// </returns>
        protected internal virtual bool decodeFrame()
        {
            try
            {
                AudioDevice out_Renamed = audio;
                if (out_Renamed == null)
                {
                    return(false);
                }

                Header h = bitstream.readFrame();

                if (h == null)
                {
                    return(false);
                }

                // sample buffer set when decoder constructed
                SampleBuffer output = (SampleBuffer)decoder.decodeFrame(h, bitstream);

                lock (this)
                {
                    out_Renamed = audio;
                    if (out_Renamed != null)
                    {
                        out_Renamed.write(output.Buffer, 0, output.BufferLength);
                    }
                }

                bitstream.closeFrame();
            }
            catch (System.SystemException ex)
            {
                throw new JavaLayerException("Exception decoding audio frame", ex);
            }

            /*
             * catch (IOException ex)
             * {
             * System.out.println("exception decoding audio frame: "+ex);
             * return false;
             * }
             * catch (BitstreamException bitex)
             * {
             * System.out.println("exception decoding audio frame: "+bitex);
             * return false;
             * }
             * catch (DecoderException decex)
             * {
             * System.out.println("exception decoding audio frame: "+decex);
             * return false;
             * }*/
            return(true);
        }
Beispiel #39
0
        public NativeRenderThread(int index, CpuBvhIntersectionEngine device, RayEngineScene scn, bool lowLatency, ImageFilm pixelDevice, ISampler sampler, SurfaceSampler ss)
            : base(index, scn) {
            intersectionDevice = device;

            // Allocate buffers

            // Sample buffer
            var sampleBufferSize = lowLatency ? (SAMPLE_BUFFER_SIZE / 4) : SAMPLE_BUFFER_SIZE;
            sampleBuffer = new SampleBuffer(sampleBufferSize);

            // Ray buffer (small buffers work well with CPU)
            var rayBufferSize = 1024;

            this.sampler = sampler;


            _pathRayProcessor = new PathBuffer(scn.MaxPaths, scn, pixelDevice, new SamplingContext() { PrimarySpaceSampler = sampler, SurfaceSampler = ss, LightSampler = new LightSampler(scn)});
            this.pixelDevice = pixelDevice;

            rayBuffer = new RayBuffer(rayBufferSize);

            renderThread = null;
        }
Beispiel #40
0
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
             int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace))
                    {
                        //if (prevEvent.Has(BsdfEvent.Transmit) && bsdfEvent.Has(BsdfEvent.Transmit))
                        //{
                        //    attenuation*= hitInfo.Color * MathLab.Exp(-Math.Max(shadowRayHit.Distance, Sample.GetLazyValue()*10f));
                        //}
                        Radiance += attenuation * ((secRays[i].Throughput) / secRays[i].Pdf);
                    }

                    if (continueTrace)
                    {
                        continueRays[contCount++] = secRays[i];
                        //continueRays.Add(secRays[i]);
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }

                Array.Copy(continueRays, secRays, contCount);
                tracedShadowRayCount = contCount;
                contCount = 0;
            }
            RayHit rayHit = rayBuffer.rayHits[RayIndex];
            Vector wo = -PathRay.Dir;

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    //Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                    var sampledEnvironment = this.scene.SampleEnvironment(ref wo);
                    Radiance.MAdd(ref sampledEnvironment , ref Throughput);
                }
                Splat(consumer);

                return;
            }

            var bsdf = SurfaceSampler.GetBsdf(ref PathRay, ref rayHit, ref currentMedium, false, this.Sample.GetLazyValue());

            //var mesh = scene.GetMeshByTriangleIndex(currentTriangleIndex);
            //rayHit.Index += (uint)mesh.StartTriangle;
            // Something was hit

            currentTriangleIndex = (int)rayHit.Index;

            
            //If Hit light)

            if (bsdf.IsLightSource())
            {
                //if (bsdfEvent.Has(BsdfEvent.Specular) || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        float pdf;
                        var le = lt.Emittance(ref wo, out pdf);
                        //Radiance += Throughput * le;
                        
                        Radiance.MAdd(ref Throughput, ref le);
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);

            tracedShadowRayCount = 0;
            

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = LightSampler.StrategyPdf;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                RgbSpectrum lightTroughtput = Throughput*(RgbSpectrum) bsdf.TexData.Diffuse;
                LightSampler.EvaluateShadow(bsdf, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                for (int index = 0; index < ls.Length; index++)
                {

                    if (ls[index].Pdf <= 0f)
                        continue;
                    secRays[tracedShadowRayCount].Throughput = ls[index].Spectrum.GetType() == typeof(RgbSpectrumInfo) ? (RgbSpectrum) (RgbSpectrumInfo)ls[index].Spectrum : (RgbSpectrum)ls[index].Spectrum;
                    secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                    secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                    BsdfEvent devent;
                    float pdfw, ipdfw;
                    var fs = (RgbSpectrum)bsdf.Evaluate(ref lwi, out devent, out pdfw, out ipdfw);
                    if (pdfw < MathLab.Epsilon)
                        continue;
                    secRays[tracedShadowRayCount].Throughput *= lightTroughtput * ((fs
                                                                * Vector.AbsDot(ref bsdf.HitPoint.ShadingNormal, ref lwi)));
                    if (!secRays[tracedShadowRayCount].Throughput.IsBlack())
                    {
#if DEBUG
                        RayDen.Library.Core.Components.Assert.IsNotNaN(secRays[tracedShadowRayCount].Pdf);
#endif
                        secRays[tracedShadowRayCount].Pdf *= lightStrategyPdf * pdfw;
                        secRays[tracedShadowRayCount].Pdf *= scene.ShadowRayCount;
                        tracedShadowRayCount++;
                    }
                }
            }

            float fPdf, frPdf;
            Vector wi;
            RgbSpectrum f;
            prevEvent = bsdfEvent;

            f =
                    bsdf.Sample(out wi, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), out fPdf,
                        out frPdf, out bsdfEvent);

            //if (prevEvent.Has(BsdfEvent.Transmit))
            //{
            //    Throughput *= MathLab.Exp(-rayHit.Distance)*0.1f;
            //}

            if (prevEvent.Has(BsdfEvent.Transmit) && bsdfEvent.Has(BsdfEvent.Transmit))
            {
                Throughput *= MathLab.Exp(-rayHit.Distance)*0.2f;
            }


            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            Throughput *= (f * (RgbSpectrum)bsdf.HitPoint.Color) / fPdf;//* (RgbSpectrum)bsdf.HitPoint.Color

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;


#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
Beispiel #41
0
        public override sealed void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
             int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace))
                    {

                        Radiance += attenuation * ((secRays[i].Throughput) / secRays[i].Pdf);
                        pathWeight *= secRays[i].Pdf;
                    }

                    if (continueTrace)
                    {
                        continueRays[contCount++] = secRays[i];
                        //continueRays.Add(secRays[i]);
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }

                Array.Copy(continueRays, secRays, contCount);
                tracedShadowRayCount = contCount;
                contCount = 0;
            }
            RayHit rayHit = rayBuffer.rayHits[RayIndex];
            Vector wo = -PathRay.Dir;

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    //Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                    var sampledEnvironment = this.scene.SampleEnvironment(ref wo);
                    Radiance.MAdd(ref sampledEnvironment , ref Throughput);
                }
                Splat(consumer);

                return;
            }

            //var mesh = scene.GetMeshByTriangleIndex(currentTriangleIndex);
            //rayHit.Index += (uint)mesh.StartTriangle;
            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                Debugger.Break();
            }
            //If Hit light)

            if (hitInfo.IsLight)
            {
                if (specularBounce || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        float pdf;
                        var le = hitInfo.Color * lt.Emittance(ref wo, out pdf);
                        //Radiance += Throughput * le;
                        
                        Radiance.MAdd(ref Throughput, ref le);
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);

            tracedShadowRayCount = 0;
            var bsdf = hitInfo.MMaterial;

            if (!hitInfo.TextureData.Alpha.IsBlack())
            {
                Throughput *= (RgbSpectrum.UnitSpectrum() - (RgbSpectrum) hitInfo.TextureData.Alpha);
                PathRay = new RayData(hitPoint, -wo);
                return;
            }

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = LightSampler.StrategyPdf;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                RgbSpectrum lightTroughtput = Throughput * hitInfo.Color;
                LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(),
                                            Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                for (int index = 0; index < ls.Length; index++)
                {

                    if (ls[index].Pdf <= 0f)
                        continue;
                    secRays[tracedShadowRayCount].Throughput = ls[index].Spectrum.GetType() == typeof(RgbSpectrumInfo) ? (RgbSpectrum) (RgbSpectrumInfo)ls[index].Spectrum : (RgbSpectrum)ls[index].Spectrum;
                    secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                    secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                    RgbSpectrum fs;
                    hitInfo.MMaterial.f(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
                    secRays[tracedShadowRayCount].Throughput *= lightTroughtput *
                                                                Vector.AbsDot(ref hitInfo.Normal, ref lwi) *
                                                                fs;
                    if (!secRays[tracedShadowRayCount].Throughput.IsBlack())
                    {
#if DEBUG
                        RayDen.Library.Core.Components.Assert.IsNotNaN(secRays[tracedShadowRayCount].Pdf);
#endif
                        secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf;
                        LightSample = ls[index];
                        tracedShadowRayCount++;
                    }
                }
            }

            float fPdf = 0f;
            var wi = new Vector();
            RgbSpectrum f;
            hitInfo.TextureData.Throughput = Throughput;
            f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue()
                                , ref hitInfo.TextureData, out fPdf, out specularBounce);

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            CurrentVertices.Add(new PathVertex()
            {
                BsdfPdf = fPdf,
                Throughput = Throughput,
                GeoNormal = hitInfo.Normal,
                HitPoint = hitPoint,
                HitType = PathVertexType.Geometry,
                IncomingDirection = wi,
                Material = bsdf,
                OutgoingDirection = wo,
                RayDistance = rayHit.Distance,
                SampleU = rayHit.U,
                SampleV = rayHit.V,
                ShadingNormal = hitInfo.ShadingNormal,
                TexCoords = hitInfo.TexCoords,
                rrWeight = 1f,
            });
            pathWeight *= fPdf;
            Throughput *= (f * hitInfo.Color) / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    CurrentVertices[CurrentVertices.Count - 1].rrWeight = 1f/prob;
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;


#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
Beispiel #42
0
 public virtual void Advance(RayBuffer rayBuffer, SampleBuffer<IColorType> consumer)
 {
     Splat(consumer);
     InitPath(this.Processor);
 }
Beispiel #43
0
 public virtual void Splat(SampleBuffer<IColorType> sampleBuffer)
 {
     Radiance = new RgbColor(Processor.samplers.PrimarySpaceSampler.GetSample());
     sampleBuffer.SplatSample(imageSample.X, imageSample.Y, ref Radiance);
 }
Beispiel #44
0
 public override void Splat(SampleBuffer sampleBuffer)
 {
     sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref this.Radiance);
 }
Beispiel #45
0
        public override void Splat(SampleBuffer sampleBuffer)
        {
            //Check tentative prob
            //Add contribution
            //Change state
            // Change sample state in init by ChangedState

            var yImportance = sampler.EvalImportance(ref Throughput, pathWeight);
            float sampleWeight = yImportance;
            if (yImportance<=0f)
                goto @init;

            var yContribution = Radiance / yImportance;
            bool accept;
            float a = 0f;
            if (!sampler.ImportanceReady)
            {
                sampler.Add_B(ref yContribution);
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref Radiance);
                this.InitPath(this.pathIntegrator);
                return;
            }

            if (yImportance > 0f)
            {
                if ((SamplerState != MCMCSamplerState.SmallStep || xImportance <= 0f || mutate))
                {
                    SwitchToSmallStep(yImportance, pathWeight, ref yContribution);
                    goto init;
                    //Print(string.Format("{0} changed state to {1}", this.SamplerID, this.SamplerState));
                }
                else if (SamplerState == MCMCSamplerState.SmallStep)
                {
                    a = Math.Min(1f, (yImportance/xImportance));
                    //contrib = (contrib / sampler.Importance) / sampler.MaxMutations;
                    sampleWeight = a;
                    this.mutationsCount++;

                    if (sampler.NextFloat() < a)
                    {
                        xImportance = yImportance;
                        this.xContribution = yContribution;
                        //this.TentativeSample = new Sample(this.Sample);
                        Push();
                        accept = true;
                        //this.pathWeight = a;
                    }
                    else
                    {
                        if (!this.Pop())
                        {
                            //Print("Chain restart - stack empty - mutations " + mutationsCount);
                            //sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref contrib, 1f-a);
                            this.Sample = new Sample(this.TentativeSample);
                            rejectCount++;
                            this.pathWeight = this.TentativeWeight;
                        }

                        //Splat = false;
                        //return;
                    }
                    /*
                   
                         * */
                    //var newSample = sampler.GetNextSample(this.Sample, I, oldI, 1.0f, ref contrib, out outC, out newW, false);
                }

               

             
            }
            else if (xImportance >= 0f && this.SamplerState == MCMCSamplerState.SmallStep)
            {
                if (!this.Pop())
                {
                    if (this.TentativeSample != null)
                    {
                        //Print("Chain restart - stack empty - mutations " + mutationsCount);
                        //sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref contrib, 1f-a);
                        this.Sample = new Sample(this.TentativeSample);
                        rejectCount++;
                        this.pathWeight = this.TentativeWeight;
                    }
                    else
                    {
                        this.SamplerState = MCMCSamplerState.LargeStep;
                    }
                }

            }

            if (!xContribution.IsBlack())
            {
                //sampleWeight *= 1f/pathWeight;
                //contrib *= (1f/sampler.MaxMutations);
                //contrib *= new RgbSpectrum((float)this.sampler.B[0],(float)this.sampler.B[1],(float)this.sampler.B[2]);
                var contribution = xContribution;
                /*
                if (accept)
                {
                    contribution *= sampleWeight*sampler.Importance;
                }
                else
                {
                    contribution *= (1f - sampleWeight) * sampler.Importance;
                }
                */

                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref contribution);
            }

            if ((mutationsCount >= sampler.MaxMutations) & (sampler.NextFloat() > (1f - sampler.LargeStepProb)))//time > mutationsCount || 
            {
                this.SamplerState = MCMCSamplerState.LargeStep;
                this.time = 0;
                //Print(string.Format("{0} changed state to {1}", this.SamplerID, this.SamplerState));
                //Print("Chain restart - max mutations");
            }
            @init:
           
            this.InitPath(this.pathIntegrator);
        }
Beispiel #46
0
 internal override void Splat(SampleBuffer buffer)
 {
     //base.Splat(buffer);
 }
Beispiel #47
0
        public override void Splat(SampleBuffer sampleBuffer)
        {
            //Check tentative prob
            //Add contribution
            //Change state
            // Change sample state in init by ChangedState



            var yImportance = sampler.EvalImportance(ref Throughput, pathWeight);
            float sampleWeight = 1f;

            var yContribution = Radiance;

            var contrib = yContribution;
            if (!sampler.ImportanceReady)
            {
                sampler.Add_B(ref yContribution);
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref Radiance);
                this.InitPath(this.pathIntegrator);
                return;
            }

            if (yImportance > 0f)
            {
                if (sampler.SamplerState == MCMCSamplerState.SmallStep)
                {
                    var a = Math.Min(1f, (Throughput.y() / xThroughput.y()));

                    if (sampler.NextFloat() < a)
                    {
                        xImportance = yImportance;
                        this.xContribution = yContribution;
                        sampleWeight = a;
                        contrib = yContribution;
                    }
                    else
                    {
                        contrib = xContribution;
                        sampleWeight = 1f - a;
                    }
                }
                else
                {
                    if (xImportance <= 0f && xContribution.IsBlack())
                    {
                        xImportance = yImportance;
                        this.xContribution = yContribution;
                        xThroughput = Throughput;
                        contrib = yContribution;
                    }
                }
            }


            RgbSpectrum c = contrib * sampleWeight * (sampler.Importance.y() / sampler.MaxMutations) * sampler.LargeStepProb; ;
            //var c = Radiance*sampleWeight*sampler.Br;
            sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref c);
            this.InitPath(this.pathIntegrator);
        }
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            base.Advance(rayBuffer, consumer);

            RayHit rayHit = rayBuffer.rayHits[RayIndex];

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].currentShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].shadowRay, out attenuation, out continueTrace))
                    {
                        //                            Radiance.MADD()
                        Radiance += ((secRays[i].color) / secRays[i].pdf);
                        pathWeight *= secRays[i].pdf;
                        var d = secRays[i].shadowRay.Point(shadowRayHit.Distance);
                        var pix = scene.Camera.UnProject(ref d);
                        this.Splat(consumer, pix.x, 720f - pix.y, ref Radiance );
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }
                tracedShadowRayCount = 0;

            }

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    RgbSpectrum env;
                    this.SampleEnvironment(ref PathRay.Dir, out env);
                    Radiance += env * Throughput;
                }
                Splat(consumer);

                return;
            }

            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, IntersectionOptions.ResolveObject);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo, IntersectionOptions.ResolveObject);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                Debugger.Break();
            }
            Vector wo = -PathRay.Dir;
            var hitPoint = PathRay.Point(rayHit.Distance);

            //If Hit light)
            if (hitInfo.IsLight)
            {
                //if (specularBounce || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        var le = (RgbSpectrum)(lt.Le(ref wo));
                        Throughput *= le;
                        AddEyeRay(ref hitPoint, ref wo, ref Throughput, 1f);
                        PathState = PathTracerPathState.ShadowRaysOnly;
                        return;
                    }
                }
           }


            var bsdf = hitInfo.MMaterial;

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = 1f;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                var lightTroughtput = Throughput*hitInfo.Color;

                AddEyeRay(ref hitPoint, ref wo, ref lightTroughtput, lightStrategyPdf );

           }

            float fPdf = 0f;
            var wi = new Vector();
            RgbSpectrum f;
     
            f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                Sample.GetLazyValue(), Sample.GetLazyValue(),
                                Sample.GetLazyValue(), ref hitInfo.TextureData,
                                out fPdf, out specularBounce)*hitInfo.Color;

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= f / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
        public override void Splat(SampleBuffer sampleBuffer)
        {
            if (!mutate)
            {
                if (!Radiance.IsBlack())
                {
                    XRadiance = Radiance;
                    xPathDensity = pathDensity;
                }
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref this.Radiance);
                this.InitPath(pathIntegrator);
            }
            else
            {
                if (!Radiance.IsBlack())
                {

                    var Tyx = pathDensity;
                    var Txy = xPathDensity;
                    var FY = Radiance.y();
                    var FX = XRadiance.y();
                    Radiance /= FY;
                    var Axy = Math.Min(1, (FY*Txy)/(FX*Tyx));
                    if (Sample.GetLazyValue() < Axy)
                    {
                        xPathDensity = pathDensity;
                        XRadiance = Radiance;
                    }
                    else
                    {
                        RestorePath();
                    }
                }
                else
                {
                    RestorePath();
                }
                var rad = this.XRadiance * (1f / MaxMutations);
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref rad);
                this.InitPath(pathIntegrator);
            }


        }
Beispiel #50
0
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif


            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
               (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace))
                    {
                        Radiance += ((secRays[i].Throughput) / secRays[i].Pdf);
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }
                tracedShadowRayCount = 0;
            }
            var rayHit = rayBuffer.rayHits[RayIndex];
            var wo = -PathRay.Dir;

            depth++;
            var missed = rayHit.Index == 0xffffffffu;

            if (missed || depth > scene.MaxPathDepth)
            {
                if (specularBounce && missed)
                {
                    Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                }
                Splat(consumer);

                return;
            }

            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            //If Hit light)
            if (hitInfo.IsLight)
            {
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        var le = (RgbSpectrum)(RgbSpectrumInfo)(lt.Le(ref PathRay.Dir));
                        Radiance += Throughput * le;
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);
            tracedShadowRayCount = 0;

            if (hitInfo.MMaterial.IsDiffuse())
            {
                float lightStrategyPdf = LightSampler.StrategyPdf;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                RgbSpectrum lightTroughtput = Throughput * hitInfo.Color;
                LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(),
                                            Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                for (int index = 0; index < ls.Length; index++)
                {

                    if (ls[index].Pdf <= 0f || float.IsNaN(ls[index].Pdf))
                        continue;
                    secRays[tracedShadowRayCount].Throughput = ls[index].Spectrum.GetType() == typeof(RgbSpectrumInfo) ? (RgbSpectrum)(RgbSpectrumInfo)ls[index].Spectrum : (RgbSpectrum)ls[index].Spectrum;
                    secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                    secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                    RgbSpectrum fs;
                    hitInfo.MMaterial.f(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
                    secRays[tracedShadowRayCount].Throughput *= lightTroughtput *
                                                                Vector.AbsDot(ref hitInfo.Normal, ref lwi) *
                                                                fs;
                    if (!secRays[tracedShadowRayCount].Throughput.IsBlack())
                    {
#if DEBUG
                        RayDen.Library.Core.Components.Assert.IsNotNaN(secRays[tracedShadowRayCount].Pdf);
#endif
                        secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf * scene.ShadowRayCount;
                        tracedShadowRayCount++;
                    }
                }
            }



            float fPdf;
            Vector wi;

            var f = hitInfo.MMaterial.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                                      Sample.GetLazyValue(), Sample.GetLazyValue(),
                                                      Sample.GetLazyValue(), ref hitInfo.TextureData,
                                                      out fPdf, out specularBounce);

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= (f * hitInfo.Color) / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {

                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
Beispiel #51
0
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            base.Advance(rayBuffer, consumer);

            RayHit rayHit = rayBuffer.rayHits[RayIndex];

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    vertices[currentVertex].Event = BsdfEvent.Environment;
                    vertices[currentVertex++].ThroughtPut = this.SampleEnvironment(PathRay.Dir);
                }
                Splat(consumer);

                return;
            }

            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo.IsLight)
            {
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    //if (lt != null)
                    {
                        var le = (RgbSpectrum)(RgbSpectrumInfo)(lt.Le(ref PathRay.Dir));
                        vertices[currentVertex].Event = BsdfEvent.Light;
                        vertices[currentVertex++].ThroughtPut = le;
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);
            vertices[currentVertex].HitPoint = hitPoint;

            Vector wo = -PathRay.Dir;
            tracedShadowRayCount = 0;

            float fPdf;
            Vector wi;
            BsdfEvent @evt;
            RgbSpectrum f = hitInfo.MMaterial.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                                      Sample.GetLazyValue(), Sample.GetLazyValue(),
                                                      Sample.GetLazyValue(), ref hitInfo.TextureData,
                                                      out fPdf, out @evt);
            specularBounce = evt.Has(BsdfEvent.Specular);
            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PurePathTracerPathState.ShadowRaysOnly;
                else
                {
                    vertices[currentVertex].Event = BsdfEvent.Absorb;
                    Splat(consumer);
                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= (f * hitInfo.Color) / fPdf;
            vertices[currentVertex].HitPoint = hitPoint;
            vertices[currentVertex].Wi = wi;
            vertices[currentVertex].Wo = wo;
            vertices[currentVertex].ShadeNormal = hitInfo.ShadingNormal;
            vertices[currentVertex].TriangleIndex = currentTriangleIndex;
            vertices[currentVertex].Bsdf = hitInfo.MMaterial;
            vertices[currentVertex].Event = @evt;
            vertices[currentVertex].BsdfSample = f;
            vertices[currentVertex].BsdfWeight = fPdf;
            vertices[currentVertex].ThroughtPut = (f * hitInfo.Color) / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    vertices[currentVertex].ThroughtPut/=prob;
                    vertices[currentVertex].RRProbability = 1f / prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PurePathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        vertices[currentVertex].Event = BsdfEvent.Absorb;

                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PurePathTracerPathState.NextVertex;
            currentVertex++;
#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
Beispiel #52
0
        public override void Splat(SampleBuffer sampleBuffer)
        {
            var thr = new RgbSpectrum(1f);
            for (int i = 0; i < currentVertex; i++)
            {
                switch (vertices[i].Event)
                {
                    //case BsdfEvent.Absorb:
                    case BsdfEvent.Light:
                    case BsdfEvent.Environment:
                            Radiance += thr*vertices[i].ThroughtPut;

                        goto absorb;
                    default:
                        if (!vertices[i].ThroughtPut.IsBlack())
                            thr *= vertices[i].ThroughtPut*vertices[currentVertex].RRProbability;
                        //else thr *= vertices[i].ThroughtPut * vertices[currentVertex].RRProbability;
                        break;
                }
            }

            
            @absorb:

            if (!this.Radiance.IsBlack())
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref this.Radiance);
            InitPath(this.pathIntegrator);
        }
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try
            {
#endif

                if ((State != RayTracerPathState.Eye) && (tracedShadowRayCount > 0))
                {
                    for (int i = 0; i < tracedShadowRayCount; ++i)
                    {
                        RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                        RgbSpectrum attenuation;
                        bool continueTrace;
                        if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation,
                            out continueTrace))
                        {
                            Radiance += attenuation*((secRays[i].Throughput)/secRays[i].Pdf);
                            pathWeight *= secRays[i].Pdf;
                        }


                    }

                    if (State == RayTracerPathState.OnlyShadow)
                    {
                        Splat(consumer);
                        return;
                    }

                    tracedShadowRayCount = 0;
                }

                var rayHit = rayBuffer.rayHits[RayIndex];
                var wo = -PathRay.Dir;

                depth++;
                var missed = rayHit.Index == 0xffffffffu;
                if (missed || State == RayTracerPathState.OnlyShadow || depth > scene.MaxPathDepth)
                {
                    if (missed)
                    {
                        //Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                        var sampledEnvironment = this.scene.SampleEnvironment(ref wo);
                        Radiance.MAdd(ref sampledEnvironment, ref Throughput);
                    }
                    Splat(consumer);
                    return;
                }

                if (hitInfo == null)
                {
                    hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
                }
                else
                {
                    SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
                }

                currentTriangleIndex = (int) rayHit.Index;
                var hitPoint = PathRay.Point(rayHit.Distance);

                tracedShadowRayCount = 0;
                var bsdf = hitInfo.MMaterial;
                if (bsdf.IsDiffuse())
                {
                    float lightStrategyPdf = LightSampler.StrategyPdf;
                    //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                    RgbSpectrum lightTroughtput = Throughput*hitInfo.Color;
                    LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(),
                        Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                    for (int index = 0; index < ls.Length; index++)
                    {

                        if (ls[index].Pdf <= 0f)
                            continue;
                        secRays[tracedShadowRayCount].Throughput = ls[index].Spectrum.GetType() ==
                                                                   typeof (RgbSpectrumInfo)
                            ? (RgbSpectrum) (RgbSpectrumInfo) ls[index].Spectrum
                            : (RgbSpectrum) ls[index].Spectrum;
                        secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                        secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                        Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                        RgbSpectrum fs;
                        hitInfo.MMaterial.f(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo,
                            ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
                        secRays[tracedShadowRayCount].Throughput *= lightTroughtput*
                                                                    Vector.AbsDot(ref hitInfo.Normal, ref lwi)*
                                                                    fs;
                        if (!secRays[tracedShadowRayCount].Throughput.IsBlack())
                        {
#if DEBUG
                            RayDen.Library.Core.Components.Assert.IsNotNaN(secRays[tracedShadowRayCount].Pdf);
#endif
                            secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf;
                            tracedShadowRayCount++;
                        }
                    }
                }

                if (bsdf.IsSpecular() || bsdf.IsRefractive() && depth < scene.MaxPathDepth)
                {
                    var fPdf = 0f;
                    var wi = new Vector();
                    RgbSpectrum f;
                    hitInfo.TextureData.Throughput = Throughput;
                    f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                        Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue()
                        , ref hitInfo.TextureData, out fPdf, out specularBounce);
                    if ((fPdf <= 0.0f) || f.IsBlack())
                    {
                        if (tracedShadowRayCount > 0)
                            State = RayTracerPathState.OnlyShadow;
                        else
                        {
                            Splat(consumer);

                        }
                        return;
                    }
                    pathWeight *= fPdf;
                    Throughput *= (f)/fPdf;
                    State = RayTracerPathState.Reflection;
                    PathRay.Org = hitPoint;
                    PathRay.Dir = wi.Normalize();
                    //Radiance += Throughput;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        State = RayTracerPathState.OnlyShadow;
                    else
                        Splat(consumer);
                }
#if VERBOSE
            }
            catch (Exception ex)
            {
                Tracer.TraceLine(ex.Message);
                throw;
            }

#endif
        }
Beispiel #54
0
        public override void Splat(SampleBuffer sampleBuffer)
        {
            if (!this.Radiance.IsBlack())
            {
                var rgb = new RgbSpectrum();//= this.Radiance.ToXyz();
                this.Radiance.TransformToRgb(out rgb);

                sampleBuffer.SplatSample((float)this.Sample.imageX, (float)this.Sample.imageY, ref rgb);

            }
            InitPath(this.Buffer);
        }
        public override void Splat(SampleBuffer sampleBuffer)
        {
#if VERBOSE
            this.pathIntegrator.splattedCount++;
#endif

            if (State == RayTracerPathState.OnlyShadow || State == RayTracerPathState.Eye || depth >= scene.MaxPathDepth)
            {
                if (Radiance.IsBlack() && Throughput.Average < 0.99f)
                {
                    Radiance += Throughput * hitInfo.Color;
                }
                sampleBuffer.SplatSample(this.Sample.imageX, this.Sample.imageY, ref this.Radiance);
            }
            this.InitPath(pathIntegrator);
        }
Beispiel #56
0
        public override sealed void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.VolumeShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace))
                    {
                        Radiance += attenuation * ((secRays[i].Throughput) / secRays[i].Pdf);
                        pathWeight *= secRays[i].Pdf;
                    }

                    if (continueTrace)
                    {
                        continueRays[contCount++] = secRays[i];
                        //continueRays.Add(secRays[i]);
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }

                Array.Copy(continueRays, secRays, contCount);
                tracedShadowRayCount = contCount;
                contCount = 0;
            }
            RayHit rayHit = rayBuffer.rayHits[RayIndex];
            Vector wo = -PathRay.Dir;

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    //Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                    var sampledEnvironment = this.scene.SampleEnvironment(ref wo);
                    Radiance.MAdd(ref sampledEnvironment, ref Throughput);
                }
                Splat(consumer);

                return;
            }

            //var mesh = scene.GetMeshByTriangleIndex(currentTriangleIndex);
            //rayHit.Index += (uint)mesh.StartTriangle;
            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                Debugger.Break();
            }
            //If Hit light)

            if (hitInfo.IsLight)
            {
                if (specularBounce || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        float pdf;
                        var le = hitInfo.Color * lt.Emittance(ref wo, out pdf);
                        //Radiance += Throughput * le;

                        Radiance.MAdd(ref Throughput, ref le);
                    }
                }
                Splat(consumer);

                return;
            }
            var hitPoint = PathRay.Point(rayHit.Distance);
            if (inVolume && !hitInfo.isVolume)
            {
                Throughput *= Math.Exp(-rayHit.Distance*0.1f);
            }

            inVolume = false;
            if (hitInfo.isVolume)
            {


                //if (Sample.GetLazyValue() <= scene.VolumeIntegrator.GetRRProbability())
                //{
                //    RayData volumeRay = new RayData(ref PathRay.Org, ref PathRay.Dir, 0f,
                //                                    rayHit.Miss() ? 1e10f : rayHit.Distance);
                //    scene.VolumeIntegrator.GenerateLiRays(scene, Sample, ref volumeRay, volumeComp);
                //    Radiance += volumeComp.GetEmittedLight();

                //    if (volumeComp.GetRayCount() > 0)
                //    {
                //        PathState = PathTracerPathState.EyeVolume;
                //        rayHit = (rayBuffer.rayHits[RayIndex]);
                //    }
                //}

                inVolume = true;
                RgbSpectrum sigma_s = hitInfo.VolumeData.Scattering;
                RgbSpectrum sigma_a = hitInfo.VolumeData.Absorbance;
                RgbSpectrum sigma_e = hitInfo.VolumeData.Emittance;

                var distance = SampleDistance(Sample.GetLazyValue(), sigma_s.y());
                hitPoint = PathRay.Point(rayHit.Distance + distance);
                var eventEps = Sample.GetLazyValue();

                if (eventEps > (sigma_a.y() + sigma_e.y() + sigma_e.y()))
                {
                    Throughput *= RgbSpectrum.Exp(-distance * sigma_s);
                    PathRay.Org = hitPoint;
                    PathState = PathTracerPathState.NextVertex;
                    return;
                }

                if (sigma_e.y() > 0f && eventEps > sigma_e.y())
                {
                    Radiance += Throughput * sigma_e;
                    Splat(consumer);
                    return;
                }

                if (eventEps < sigma_a.y())
                {
                    Radiance += Throughput * sigma_a;
                    if (tracedShadowRayCount > 0)
                    {
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    }
                    else
                    {
                        Splat(consumer);

                        return;
                    }

                }
                else //if (eventEps > sigma_a.y() )
                {
                    var pdf = 1f - MathLab.Exp(-sigma_s.y() * distance);
                    var vwi = new Vector(Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue());
                    var fp = PhaseFunctions.PhaseIsotropic(ref wo, ref vwi);


                    Throughput *= (fp * ((sigma_s+sigma_a)*0.5f) );
                    PathRay.Org = hitPoint + wo * distance;
                    PathRay.Dir = vwi.Normalize();
                    PathState = PathTracerPathState.NextVertex;
                    return;
                }
            }


            tracedShadowRayCount = 0;
            var bsdf = hitInfo.MMaterial;

            if (!hitInfo.TextureData.Alpha.IsBlack())
            {
                Throughput *= (RgbSpectrum.UnitSpectrum() - (RgbSpectrum)hitInfo.TextureData.Alpha);
                PathRay = new RayData(hitPoint, -wo);
                return;
            }

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = LightSampler.StrategyPdf;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                RgbSpectrum lightTroughtput = Throughput * hitInfo.Color;
                LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(),
                                            Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                for (int index = 0; index < ls.Length; index++)
                {

                    if (ls[index].Pdf <= 0f)
                        continue;
                    secRays[tracedShadowRayCount].Throughput = ls[index].Spectrum.GetType() == typeof(RgbSpectrumInfo) ? (RgbSpectrum)(RgbSpectrumInfo)ls[index].Spectrum : (RgbSpectrum)ls[index].Spectrum;
                    secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                    secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                    RgbSpectrum fs;
                    hitInfo.MMaterial.f(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
                    secRays[tracedShadowRayCount].Throughput *= lightTroughtput *
                                                                Vector.AbsDot(ref hitInfo.Normal, ref lwi) *
                                                                fs;
                    if (!secRays[tracedShadowRayCount].Throughput.IsBlack())
                    {
#if DEBUG
                        RayDen.Library.Core.Components.Assert.IsNotNaN(secRays[tracedShadowRayCount].Pdf);
#endif
                        secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf;
                        tracedShadowRayCount++;
                    }
                }
            }

            float fPdf = 0f;
            var wi = new Vector();
            RgbSpectrum f;
            hitInfo.TextureData.Throughput = Throughput;
            f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue()
                                , ref hitInfo.TextureData, out fPdf, out specularBounce);

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= (f * hitInfo.Color) / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try
            {
#endif

            RayHit rayHit = rayBuffer.rayHits[RayIndex];

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].currentShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].shadowRay, out attenuation, out continueTrace))
                    {
                        //                            Radiance.MADD()
                        Radiance += attenuation * ((secRays[i].color) / secRays[i].pdf);
                        pathWeight *= secRays[i].pdf;
                    }
                }
                Splat(consumer);

                return;
            }

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > sceneMaxPathDepth)
            {
                if (missed)
                {
                    Radiance += this.SampleEnvironment(PathRay.Dir) * Throughput;
                }
                Splat(consumer);

                return;
            }

            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                Debugger.Break();
            }
            //If Hit light)
            if (hitInfo.IsLight)
            {
                //if (specularBounce) 
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        var le = (RgbSpectrum)(lt.Le(ref PathRay.Dir));
                        Radiance += Throughput * le;
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);

            Vector wo = -PathRay.Dir;
            tracedShadowRayCount = 0;
            var bsdf = hitInfo.MMaterial;

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = scene.ShadowRayCount;
                RgbSpectrum lightTroughtput = Throughput * hitInfo.Color;
                LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(),
                                            Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                foreach (var lightSample in ls)
                {
                    if (lightSample.Pdf <= 0f)
                        continue;
                    secRays[tracedShadowRayCount].color = (RgbSpectrum)(lightSample.Spectrum);
                    secRays[tracedShadowRayCount].pdf = lightSample.Pdf;
                    secRays[tracedShadowRayCount].shadowRay = lightSample.LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].shadowRay.Dir;
                    RgbSpectrum fs;
                    hitInfo.MMaterial.f(
                        ref secRays[tracedShadowRayCount].shadowRay.Dir,
                        ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
                    secRays[tracedShadowRayCount].color *= lightTroughtput *
                                                           Vector.AbsDot(ref hitInfo.Normal, ref lwi) *
                                                           fs;
                    if (!secRays[tracedShadowRayCount].color.IsBlack())
                    {
                        secRays[tracedShadowRayCount].pdf *= lightStrategyPdf;
                        tracedShadowRayCount++;
                    }
                }
            }


            float fPdf;
            Vector wi;

            RgbSpectrum f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                                      Sample.GetLazyValue(), Sample.GetLazyValue(),
                                                      Sample.GetLazyValue(), ref hitInfo.TextureData,
                                                      out fPdf, out specularBounce);

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= (f) / fPdf;

            if (depth > sceneMaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex)
            {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
Beispiel #58
0
        public override sealed void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                var continueRays = new List<ShadowRayInfo>();
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace))
                    {
                        //Radiance += attenuation * ((secRays[i].Throughput) / secRays[i].Pdf);
                        waveRadiance += secRays[i].Throughput[0]/secRays[i].Pdf;
                        //pathWeight *= secRays[i].Pdf;
                    }

                    if (continueTrace)
                    {
                        continueRays.Add(secRays[i]);
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }

                Array.Copy(continueRays.ToArray(), secRays, continueRays.Count);
                tracedShadowRayCount = continueRays.Count;
            }
            RayHit rayHit = rayBuffer.rayHits[RayIndex];
            Vector wo = -PathRay.Dir;

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    //Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                    //var sampledEnvironment = this.scene.SampleEnvironment(ref wo); //!
                    waveRadiance += wlSampler.SampleEnvironment(HeroWavelength, ref wo);
                    //Radiance.MAdd(ref sampledEnvironment, ref Throughput);
                }
                Splat(consumer);

                return;
            }

            //var mesh = scene.GetMeshByTriangleIndex(currentTriangleIndex);
            //rayHit.Index += (uint)mesh.StartTriangle;
            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                System.Diagnostics.Debugger.Break();
            }
            //If Hit light)

            if (hitInfo.IsLight)
            {
                if (specularBounce || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);

                    if (lt != null)
                    {
                        waveRadiance += wlSampler.SampleLight(lt, HeroWavelength);
                        //var le = hitInfo.Color * (RgbSpectrum)(lt.Le(ref wo)); //!
                        //Radiance += Throughput * le;
                        //Radiance.MAdd(ref Throughput, ref le);
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);

            tracedShadowRayCount = 0;
            var bsdf = wlSampler.GetBrdf(scene.GetMeshByTriangleIndex(currentTriangleIndex).MaterialID);

            //if (!hitInfo.TextureData.Alpha.IsBlack())
            //{
            //    Throughput *= (RgbSpectrum.UnitSpectrum() - hitInfo.TextureData.Alpha);
            //    PathRay = new RayData(hitPoint, -wo);
            //    return;
            //}

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = LightSampler.StrategyPdf;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                //RgbSpectrum lightTroughtput = Throughput * hitInfo.Color;
                float ltThroughput = waveThroughput*bsdf.Kd.Sample(HeroWavelength);
                LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(depth),
                                            Sample.GetLazyValue(2*depth+1), Sample.GetLazyValue(3*depth+2), ref ls);
                for (int index = 0; index < ls.Length; index++)
                {

                    if (ls[index].Pdf <= 0f)
                        continue;
                    ls[index].Lambda = wlSampler.SampleLight(scene.Lights[ls[index].LightIndex], HeroWavelength);
                    secRays[tracedShadowRayCount].Throughput[0] = ls[index].Lambda;
                    secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                    secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                    float fs;
                    bsdf.F(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo, ref hitInfo.ShadingNormal, HeroWavelength, out fs);
                    secRays[tracedShadowRayCount].Throughput[0] *= ltThroughput*
                                                                Vector.AbsDot(ref hitInfo.Normal, ref lwi) *
                                                                fs;
                    if (secRays[tracedShadowRayCount].Throughput[0] > 0f)
                    {
#if DEBUG
                                    RayDen.Library.Core.Components.Assert.IsNotNaN(secRays[tracedShadowRayCount].Pdf);
#endif
                        secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf;
                        tracedShadowRayCount++;
                    }
                }
            }

            float fPdf = 0f;
            var wi = new Vector();
            float f;
            BsdfSampleData bsdfSample;
            bsdf.Sample_f(ref wo, ref hitInfo.Normal, ref hitInfo.ShadingNormal, HeroWavelength, ref hitInfo.TextureData,
                                Sample.GetLazyValue(4 * depth + 3), Sample.GetLazyValue(5 * depth + 4), Sample.GetLazyValue(6 * depth + 5)
                                , out bsdfSample);
            f = bsdfSample.Lambda;
            fPdf = bsdfSample.Pdf;
            wi = bsdfSample.Wi;
            specularBounce = bsdfSample.SpecularBounce;

            if ((fPdf <= 0.0f))// || f.IsBlack()
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            waveThroughput *= f/fPdf;
            pathWeight *= fPdf;
            //Throughput *= (f * hitInfo.Color) / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(waveThroughput, scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue(7 * depth + 5))
                {
                    //Throughput /= prob;
                    waveThroughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
Beispiel #59
0
        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            base.Advance(rayBuffer, consumer);

            RayHit rayHit = rayBuffer.rayHits[RayIndex];

            Depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            var wo = -PathRay.Dir;
            if (missed || Depth > maxDepth)
            {
                if (specularBounce && missed)
                {
                    Radiance.Add(Throughput.Mul(ColorManager.Instance.Convert(this.SampleEnvironment(ref wo))));
                }
                Splat(consumer);

                return;
            }

            HitManager.Instance.EvalHit(ref PathRay, ref rayHit, ref hitInfo);

            currentTriangleIndex = (int)rayHit.Index;

            //If Hit light)
            if (hitInfo.PointType == ShadePointType.Light)
            {
                float lpdf;
                var lt = this.Buffer.SceneManager.GetLightById(hitInfo.ObjectId);
                var le = lt.Light.Emit(ref wo, out lpdf);

                Radiance.Add(Throughput.Mul(le));
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);

            tracedShadowRayCount = 0;

            float fPdf;
            Vector wi;

            float f;
            BsdfEvent @event;
            hitInfo.Brdf.Sample_f(hitInfo,
                                    Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(),
                                    out wi, out f, out fPdf, out @event);

            if ((fPdf <= 0.0f) || f<=0f)
            {
                if (tracedShadowRayCount > 0)
                    PathState = PurePathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }

            Throughput.Mul(hitInfo.GetColorInstance()).Mul(f / fPdf);

            if (Depth > maxDepth)
            {
                float prob = Math.Max(Throughput.Filter(), RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput.Mul(1f / prob);
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PurePathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PurePathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
 public virtual void Advance(RayBuffer rb, SampleBuffer sb)
 {
     
 }