public static Buffer CreateLutBuffer(float f_x, float f_y)
        {
            var filter =
                //new MitchelFilter(f_x, f_y);
            new GaussianFilter(f_x, f_y);

            float[] Gaussian2x2_filterTable = new float[16 * 16];
            for (var y = 0; y < 16; ++y)
            {
                float fy = (y + 0.5f) * 2.0f / 16.0f;
                for (var x = 0; x < 16; ++x)
                {
                    float fx = (x + 0.5f) * 2.0f / 16.0f;
                    Gaussian2x2_filterTable[x + y * 16] = filter.Evaluate(fx, fy);
                    //Max<float>(0.f, expf(-alpha * fx * fx) - expX) *Max<float>(0.f, expf(-alpha * fy * fy) - expY);
                }
            }

            BufferDesc desc = new BufferDesc()
            {
                Width = 16 * 16,
                Type = BufferType.Input,
                Format = Format.Float
            };

            Buffer res = new Buffer(ComponentPipeline.Instance.Session.OptixContext, desc);

            res.SetData(Gaussian2x2_filterTable);

            return res;
        }
Exemple #2
0
        protected OptixBuffer CreateOutputBuffer(Format format, int width, int height)
        {
            if (UsePBO)
            {
                //Allocate first the memory for the gl buffer, then attach it to OptiX.
                uint pbo = CreatePBO(format);

                OGLBufferDesc glDesc = new OGLBufferDesc()
                {
                    Width    = (uint)width,
                    Height   = (uint)height,
                    Format   = format,
                    Type     = BufferType.Output,
                    Resource = pbo
                };
                return(new OGLBuffer(OptixContext, glDesc));
            }
            else
            {
                BufferDesc desc = new BufferDesc()
                {
                    Width  = (uint)width,
                    Height = (uint)height,
                    Format = format,
                    Type   = BufferType.Output
                };
                return(new OptixBuffer(OptixContext, desc));
            }
        }
        public OptixIntersectionDevice(IRayEngineScene scene, bool lowLatency = false) : base(scene)
        {
            this.lowLatency = lowLatency;
            Context = new Context { CpuNumThreads = 4, RayTypeCount = 1, EntryPointCount = 1 };
            
            var rayBufferDesc = new BufferDesc()
            {
                Format = Format.User,
                Width = (uint)(lowLatency ? RayBuffer.RayBufferSize / 8 : RayBuffer.RayBufferSize),
                Type = BufferType.InputOutput,
                ElemSize = (uint)Marshal.SizeOf(typeof(RayData))
            };
            var rayHitBufferDesc = new BufferDesc()
            {
                Format = Format.User,
                Width =  (uint)(lowLatency ? RayBuffer.RayBufferSize / 8 : RayBuffer.RayBufferSize),
                Type = BufferType.InputOutput,
                ElemSize = (uint)Marshal.SizeOf(typeof(RayHit))
            };

            this.todoRayBuffers = new InputRayBufferCollection();
            this.doneRayBuffers = new OutputRayBufferCollection();
            this.started = false;

            Rays = new DeviceBuffer(Context, rayBufferDesc);
            RayHits = new DeviceBuffer(Context, rayHitBufferDesc);
            Context["rayHits"].Set(RayHits);
            Context["rays"].Set(Rays);
            Builder = AccelBuilder.TriangleKdTree;
            Traverser = AccelTraverser.KdTree;
            GeoGroup = new GeometryGroup(Context);
            this.SetScene(scene);
        }
Exemple #4
0
        public static Buffer CreateLutBuffer(Context optixContext, float f_x, float f_y)
        {
            var filter =
                new MitchelFilter(f_x, f_y);

            //new GaussianFilter(f_x, f_y);

            float[] Gaussian2x2_filterTable = new float[16 * 16];
            for (var y = 0; y < 16; ++y)
            {
                float fy = (y + 0.5f) * 2.0f / 16.0f;
                for (var x = 0; x < 16; ++x)
                {
                    float fx = (x + 0.5f) * 2.0f / 16.0f;
                    Gaussian2x2_filterTable[x + y * 16] = filter.Evaluate(fx, fy);
                }
            }

            BufferDesc desc = new BufferDesc
            {
                Width  = 16 * 16,
                Type   = BufferType.Input,
                Format = Format.Float
            };

            Buffer res = new Buffer(optixContext, desc);

            res.SetData(Gaussian2x2_filterTable);

            return(res);
        }
Exemple #5
0
        void createVertexBuffer(IRenderDevice device)
        {
            // Cube vertices

            //      (-1,+1,+1)________________(+1,+1,+1)
            //               /|              /|
            //              / |             / |
            //             /  |            /  |
            //            /   |           /   |
            //(-1,-1,+1) /____|__________/(+1,-1,+1)
            //           |    |__________|____|
            //           |   /(-1,+1,-1) |    /(+1,+1,-1)
            //           |  /            |   /
            //           | /             |  /
            //           |/              | /
            //           /_______________|/
            //        (-1,-1,-1)       (+1,-1,-1)
            //

            Vertex[] CubeVerts = new Vertex[]
            {
                vert(float3(-1, -1, -1), float2(0, 1)),
                vert(float3(-1, +1, -1), float2(0, 0)),
                vert(float3(+1, +1, -1), float2(1, 0)),
                vert(float3(+1, -1, -1), float2(1, 1)),

                vert(float3(-1, -1, -1), float2(0, 1)),
                vert(float3(-1, -1, +1), float2(0, 0)),
                vert(float3(+1, -1, +1), float2(1, 0)),
                vert(float3(+1, -1, -1), float2(1, 1)),

                vert(float3(+1, -1, -1), float2(0, 1)),
                vert(float3(+1, -1, +1), float2(1, 1)),
                vert(float3(+1, +1, +1), float2(1, 0)),
                vert(float3(+1, +1, -1), float2(0, 0)),

                vert(float3(+1, +1, -1), float2(0, 1)),
                vert(float3(+1, +1, +1), float2(0, 0)),
                vert(float3(-1, +1, +1), float2(1, 0)),
                vert(float3(-1, +1, -1), float2(1, 1)),

                vert(float3(-1, +1, -1), float2(1, 0)),
                vert(float3(-1, +1, +1), float2(0, 0)),
                vert(float3(-1, -1, +1), float2(0, 1)),
                vert(float3(-1, -1, -1), float2(1, 1)),

                vert(float3(-1, -1, +1), float2(1, 1)),
                vert(float3(+1, -1, +1), float2(0, 1)),
                vert(float3(+1, +1, +1), float2(0, 0)),
                vert(float3(-1, +1, +1), float2(1, 0)),
            };
            BufferDesc VertBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.VertexBuffer,
            };

            cubeVertexBuffer = device.CreateBuffer(VertBuffDesc, CubeVerts, "Cube vertex buffer");
        }
        private void LoadEnvMap()
        {
            if (mTutorial < 5)
            {
                return;
            }

            string texturePath = Path.GetFullPath(EnvMapPath);

            Bitmap image = new Bitmap(Image.FromFile(texturePath));

            if (image == null)
            {
                return;
            }

            var imgData = image.LockBits(new System.DrawingCore.Rectangle(0, 0, image.Width, image.Height),
                                         ImageLockMode.ReadWrite, image.PixelFormat);


            BufferDesc bufferDesc = new BufferDesc()
            {
                Width = (uint)image.Width, Height = (uint)image.Height, Format = Format.UByte4, Type = BufferType.Input
            };
            Buffer textureBuffer = new Buffer(OptixContext, bufferDesc);

            int stride      = imgData.Stride;
            int numChannels = 4;

            unsafe
            {
                byte *src = (byte *)imgData.Scan0.ToPointer();

                BufferStream stream = textureBuffer.Map();
                for (int h = 0; h < image.Height; h++)
                {
                    for (int w = 0; w < image.Width; w++)
                    {
                        UByte4 color = new UByte4(src[(image.Height - h - 1) * stride + w * numChannels + 2],
                                                  src[(image.Height - h - 1) * stride + w * numChannels + 1],
                                                  src[(image.Height - h - 1) * stride + w * numChannels + 0],
                                                  255);

                        stream.Write <UByte4>(color);
                    }
                }
                textureBuffer.Unmap();
            }
            image.UnlockBits(imgData);

            TextureSampler texture = new TextureSampler(OptixContext, TextureSamplerDesc.GetDefault(WrapMode.Repeat));

            texture.SetBuffer(textureBuffer);

            OptixContext["envmap"].Set(texture);
        }
Exemple #7
0
 /// <summary>
 /// descから
 /// </summary>
 /// <param name="desc"></param>
 public TextureBuffer(BufferDesc desc)
 {
     if (desc.depth > 0)
     {
         Initialize3D(desc);
     }
     else
     {
         Initialize(desc);
     }
 }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="desc"></param>
        public void Initialize(BufferDesc desc)
        {
            var device = GraphicsCore.D3D11Device;

            stride_ = desc.stride;

            BindFlags flags = BindFlags.ShaderResource;

            if (desc.bindUAV)
            {
                flags |= BindFlags.UnorderedAccess;
            }

            BufferDescription bufDesc = new BufferDescription {
                SizeInBytes         = desc.size,
                StructureByteStride = desc.stride,
                BindFlags           = flags,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage          = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
            };

            // 初期化データ
            if (desc.initData != null)
            {
                DataStream stream = new DataStream(desc.initData, true, false);
                buffer_ = new D3D11Buffer(device, stream, bufDesc);
                stream.Close();
            }
            else
            {
                buffer_ = new D3D11Buffer(device, bufDesc);
            }

            // SRV
            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription {
                Format       = Format.Unknown,
                Dimension    = ShaderResourceViewDimension.Buffer,
                ElementWidth = desc.size / desc.stride,
            };

            shaderResourceView_ = new ShaderResourceView(device, buffer_, srvViewDesc);

            if (desc.bindUAV)
            {
                UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription {
                    Dimension    = UnorderedAccessViewDimension.Buffer,
                    ElementCount = desc.size / desc.stride,
                    Flags        = UnorderedAccessViewBufferFlags.None,
                    Format       = Format.Unknown,
                };
                unorderedAccessView_ = new UnorderedAccessView(device, buffer_, uavDesc);
            }
        }
        private OptixBuffer CreateBuffer(float[] data)
        {
            BufferDesc spdBuffDesc = new BufferDesc
            {
                Width  = (ulong)data.Length,
                Format = Format.Float,
                //ElemSize = 0,
                Type = BufferType.Input
            };
            var x = new OptixBuffer(OptixContext, spdBuffDesc);

            x.SetData(data);
            return(x);
        }
Exemple #10
0
        public static IndexedMesh createIndexed <TVertex, TIndex>(IRenderDevice device, TVertex[] vertices, TIndex[] indices, string name)
            where TVertex : unmanaged
            where TIndex : unmanaged
        {
            // Find index type
            GpuValueType indexType;

            switch (Type.GetTypeCode(typeof(TIndex)))
            {
            // https://stackoverflow.com/a/4902207/126995
            case TypeCode.Int32:
            case TypeCode.UInt32:
                indexType = GpuValueType.Uint32;
                break;

            case TypeCode.Int16:
            case TypeCode.UInt16:
                indexType = GpuValueType.Uint16;
                break;

            case TypeCode.Byte:
            case TypeCode.SByte:
                indexType = GpuValueType.Uint8;
                break;

            default:
                throw new ArgumentException($"IndexedMesh.create: index type must be an integer, not { typeof( TIndex ).GetType().Name }");
            }

            // Create vertex buffer
            BufferDesc VertBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.VertexBuffer,
            };
            string vbName = nameVb(name);
            var    vb     = device.CreateBuffer(VertBuffDesc, vertices, vbName);

            // Create index buffer
            BufferDesc IndBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.IndexBuffer
            };
            string ibName = nameIb(name);
            var    ib     = device.CreateBuffer(IndBuffDesc, indices, ibName);

            // Wrap both into the object
            return(new IndexedMesh(vb, ib, indices.Length, indexType));
        }
Exemple #11
0
        /// <summary>Create immutable VB with the full-screen triangle with cropping-included texture coordinates</summary>
        public static IBuffer createVideoVertexBuffer(IRenderDevice device, CSize renderTargetSize, ref sDecodedVideoSize videoSize)
        {
            Span <sVideoVertex> data = stackalloc sVideoVertex[3];

            produceVertices(data, renderTargetSize, ref videoSize);

            BufferDesc desc = new BufferDesc(false)
            {
                uiSizeInBytes = 16 * 3,
                BindFlags     = BindFlags.VertexBuffer,
                Usage         = Usage.Static,
            };

            ReadOnlySpan <sVideoVertex> readOnly = data;

            return(device.CreateBuffer(desc, readOnly, "Video VB"));
        }
Exemple #12
0
        static IBuffer createVertexBuffer(IRenderDevice device)
        {
            Vector2[] vertices = new Vector2[4]
            {
                new Vector2(1, 0),
                new Vector2(0, 0),
                new Vector2(1, 1),
                new Vector2(0, 1),
            };
            BufferDesc VertBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.VertexBuffer,
            };

            return(device.CreateBuffer(VertBuffDesc, vertices, "Cursor vertex buffer"));
        }
Exemple #13
0
        public static void InitContext(Context context)
        {

            var pbDesc = new BufferDesc()
            {
                Format = Format.Int,
                Width = (ulong)primes.Length,
                Type = BufferType.Input
            };
            var bp = new Buffer(context, pbDesc);
            var ps = bp.Map();
            for (int i = 0; i < primes.Length; i++)
            {
                ps.Write(primes[i]);
            }
            bp.Unmap();
            context["primes"].Set(bp);
        }
Exemple #14
0
        public override void Initialize(Action<BoundingBox> setCamera, params object[] parameters)
        {
            base.Initialize(setCamera, parameters);
            string rayGenPath = PtxDir + ("raytracer.cu.ptx");
            string shaderPath = PtxDir + ("raytracer.cu.ptx");


            var Context = base.Context;
            var Width = (int)parameters[1];
            var Height = (int)parameters[2];

            var desc = new BufferDesc()
            {
                Width = (uint)Width,
                Height = (uint)Height,
                Format = Format.Float3,
                Type = BufferType.InputOutput
            };
        }
Exemple #15
0
        void createIndexBuffer(IRenderDevice device)
        {
            ushort[] Indices = new ushort[]
            {
                2, 0, 1, 2, 3, 0,
                4, 6, 5, 4, 7, 6,
                8, 10, 9, 8, 11, 10,
                12, 14, 13, 12, 15, 14,
                16, 18, 17, 16, 19, 18,
                20, 21, 22, 20, 22, 23
            };

            BufferDesc IndBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.IndexBuffer
            };

            cubeIndexBuffer = device.CreateBuffer(IndBuffDesc, Indices, "Cube index buffer");
        }
Exemple #16
0
        void createVertexBuffer(IRenderDevice device)
        {
            // Cube vertices

            //      (-1,+1,+1)________________(+1,+1,+1)
            //               /|              /|
            //              / |             / |
            //             /  |            /  |
            //            /   |           /   |
            //(-1,-1,+1) /____|__________/(+1,-1,+1)
            //           |    |__________|____|
            //           |   /(-1,+1,-1) |    /(+1,+1,-1)
            //           |  /            |   /
            //           | /             |  /
            //           |/              | /
            //           /_______________|/
            //        (-1,-1,-1)       (+1,-1,-1)
            //

            // clang-format off
            Vertex[] CubeVerts = new Vertex[8]
            {
                vert(v3(-1, -1, -1), v4(1, 0, 0, 1)),
                vert(v3(-1, +1, -1), v4(0, 1, 0, 1)),
                vert(v3(+1, +1, -1), v4(0, 0, 1, 1)),
                vert(v3(+1, -1, -1), v4(1, 1, 1, 1)),

                vert(v3(-1, -1, +1), v4(1, 1, 0, 1)),
                vert(v3(-1, +1, +1), v4(0, 1, 1, 1)),
                vert(v3(+1, +1, +1), v4(1, 0, 1, 1)),
                vert(v3(+1, -1, +1), v4(0.2f, 0.2f, 0.2f, 1)),
            };
            BufferDesc VertBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.VertexBuffer,
            };

            cubeVertexBuffer = device.CreateBuffer(VertBuffDesc, CubeVerts, "Cube vertex buffer");
        }
Exemple #17
0
        void createIndexBuffer(IRenderDevice device)
        {
            // clang-format off
            uint[] Indices = new uint[]
            {
                2, 0, 1, 2, 3, 0,
                4, 6, 5, 4, 7, 6,
                0, 7, 4, 0, 3, 7,
                1, 0, 4, 1, 4, 5,
                1, 5, 2, 5, 6, 2,
                3, 6, 7, 3, 2, 6
            };
            // clang-format on

            BufferDesc IndBuffDesc = new BufferDesc(false)
            {
                Usage     = Usage.Static,
                BindFlags = BindFlags.IndexBuffer
            };

            cubeIndexBuffer = device.CreateBuffer(IndBuffDesc, Indices, "Cube index buffer");
        }
Exemple #18
0
        void createStaticCBuffer(CSize size, double dpiScaling)
        {
            var data = new StaticConstantsBuffer();

            data.pixelSizeAndDpiScaling.X = 2.0f / size.cx;
            data.pixelSizeAndDpiScaling.Y = 2.0f / size.cy;
            data.pixelSizeAndDpiScaling.Z = (float)dpiScaling;
            data.pixelSizeAndDpiScaling.W = (float)(1.0 / dpiScaling);

            pixelSizeAndDpiScaling = data.pixelSizeAndDpiScaling;

            BufferDesc desc = new BufferDesc(false)
            {
                uiSizeInBytes = 16,
                BindFlags     = BindFlags.UniformBuffer,
                Usage         = Usage.Static,
            };

            ComUtils.clear(ref m_staticCBuffer);
            using (var device = context.renderContext.device)
                m_staticCBuffer = device.CreateBuffer(desc, ref data, "StaticConstantsBuffer");
        }
        private void CreateLights()
        {
            var light = new ParallelogramLight
            {
                corner = new Vector3(2.8096f, 17.1165f, 2.3659f),
                v1     = new Vector3(-5.0f, 0.0f, 0.0f),
                v2     = new Vector3(0.0f, 0.0f, 5.0f)
            };

            light.normal   = Vector3.Normalize(Vector3.Cross(light.v1, light.v2));
            light.emission = new Vector3(15.0f, 15.0f, 5.0f);

            var desc = new BufferDesc {
                Width = 1u, Format = Format.User, Type = BufferType.Input, ElemSize = (uint)Marshal.SizeOf(typeof(ParallelogramLight))
            };
            var lightBuffer = new OptixBuffer(OptixContext, desc);
            var stream      = lightBuffer.Map();

            stream.Write(light);
            lightBuffer.Unmap();

            OptixContext["plights"].Set(lightBuffer);
        }
Exemple #20
0
        protected OptixDotNet.Buffer CreateOutputBuffer(Format format, int width, int height)
        {
            if (UsePBO)
            {
                //Allocate first the memory for the gl buffer, then attach it to OptiX.
                uint pbo = CreatePBO(format);

                OGLBufferDesc glDesc = new OGLBufferDesc()
                {
                    Width = (uint)width,
                    Height = (uint)height,
                    Format = format,
                    Type = BufferType.Output,
                    Resource = pbo
                };
                return new OGLBuffer(Context, glDesc);
            }
            else
            {
                BufferDesc desc = new BufferDesc()
                {
                    Width = (uint)width,
                    Height = (uint)height,
                    Format = format,
                    Type = BufferType.Output
                };
                return new OptixDotNet.Buffer(Context, desc);
            }
        }
Exemple #21
0
        public override void SetupScene(SceneGraph scene)
        {
            Tracer.Print("SceneSetup", "Start building scene data");

            builder.Build(scene);

            Tracer.Print("SceneSetup", "Creating buffers");

            var optixContext = ComponentPipeline.Instance.Session.OptixContext;
            ComponentPipeline.Instance.Session.Frame.CurrentCamera = builder.Camera;

            var spdBuffDesc = new BufferDesc
            {
                Width = outputBuffer.Width + 1,
                Height = outputBuffer.Height + 1,
                Depth = outputBuffer.Depth,
                Format = Format.Float3,
                Type = BufferType.InputOutput
            };
            hdrBuffer = new Buffer(optixContext, spdBuffDesc);

            hdrBuffer.SetData(new Vector3[spdBuffDesc.Width * spdBuffDesc.Height]);

            var rndBuffDesc = new BufferDesc
            {
                Width = outputBuffer.Width + 1,
                Height = outputBuffer.Height + 1,
                Depth = outputBuffer.Depth,
                Format = Format.UInt,
                Type = BufferType.InputOutput
            };
            rndBuffer = new Buffer(optixContext, rndBuffDesc);
            GenerateSeeds();
            optixContext["rnd_seeds"].Set(rndBuffer);
            optixContext["hdr_buffer"].Set(hdrBuffer);

            optixContext["top_object"].Set(ComponentPipeline.Instance.Session.Frame.TopObject);
            optixContext["output_buffer"].Set(outputBuffer);
            optixContext["scene_epsilon"].Set(0.00001f);
            optixContext["rr_begin_depth"].Set(rrBeginDepth);
            optixContext["max_depth"].Set(maxDepth);
            optixContext["sqrt_num_samples"].Set(sqrtSamples);
            optixContext["bad_color"].SetFloat3(new Vector3(1.0f, 0.0f, 0.0f));
            //optixContext["bg_color"].Set(100 / 255.0f, 149 / 255.0f, 237 / 255.0f);
            optixContext["bg_color"].Set(0f,0f,0f);

            optixContext["lights"].Set(ComponentPipeline.Instance.Session.Frame.LightBuffer);
            optixContext["lightTriangles"].Set(ComponentPipeline.Instance.Session.Frame.LightTrianglesBuffer);

            optixContext["Y_log_av"].Set(yAvg);
            optixContext["Y_max"].Set(yMax);
            optixContext["gamma_value"].Set(gamma_value);

            QMC.InitContext(optixContext);
            Tracer.Print("SceneSetup", "Optix context compilation.");

            ComponentPipeline.Instance.Session.OptixContext.Compile();
            ComponentPipeline.Instance.Session.OptixContext.BuildAccelTree();

            Tracer.Print("SceneSetup", "Finished.");
        }
        private void SetDefaultMaterialProperties(GeometryInstance instance, Material mtrl, SceneMaterial material)
        {
            var brdf = (BrdfTypes)(int)material["brdf_id"];
            if (brdf == BrdfTypes.BRDF_TYPE_GLOSSY_REFLECTION_MEASURED)
            {
                int th, td, pd;
                string[] names =
                {
                    "chrome-steel.binary", "gold-metallic-paint.binary", "green-acrylic.binary", "chrome-steel.binary",
                    "color-changing-paint1.binary", "colonial-maple-223.binary", "dark-blue-paint.binary",
                    "green-fabric.binary",
                    "green-plastic.binary", "hematite.binary", "nylon.binary", "pearl-paint.binary"
                };

                Random rnd = new Random();
                string fileName = string.Format(@"F:\3D\Brdfs\merl\{0}", names[rnd.Next(0, names.Length - 1)]);
                Trace.TraceInformation("Loading material data for " + fileName);
                var data =
                    OptixMaterialFactory.FileHelper.Read(fileName, out th, out td, out pd)
                        .Select(i => (float)i)
                        .ToArray();
                mtrl["nThetaH"].Set(th);
                mtrl["nThetaD"].Set(td);
                mtrl["nPhiD"].Set(pd);
                var bDesc = new BufferDesc()
                {
                    Width = (uint)data.Length,
                    Format = Format.Float,
                    Type = BufferType.Input
                };
                var viBuffer = new Buffer(Session.OptixContext, bDesc);
                viBuffer.SetData(data);
                mtrl["brdf"].Set(viBuffer);
            }
            else
            {
                var bDesc = new BufferDesc()
                {
                    Width = (uint)1,
                    Format = Format.Float,
                    Type = BufferType.Input
                };
                var viBuffer = new Buffer(Session.OptixContext, bDesc);
                viBuffer.SetData(new[] { 1u });
                mtrl["brdf"].Set(viBuffer);
            }
        }
Exemple #23
0
        public override void SetupScene(Scene.SceneGraph scene)
        {
            Tracer.Print("SceneSetup", "Start building scene data");

            this.SafeExec(() => builder.Build(scene), ex => { Trace.WriteLine(ex.StackTrace); });

            Tracer.Print("SceneSetup", "Creating buffers");

            var optixContext = ComponentPipeline.Instance.Session.OptixContext;

            UpdateDescriptionBuffer();

            this.Cameras = builder.Cameras;
            ComponentPipeline.Instance.Session.Frame.CurrentCamera = builder.Camera;

            var spdBuffDesc = new BufferDesc
            {
                Width = outputBuffer.Width,
                Height = outputBuffer.Height,
                Depth = outputBuffer.Depth,
                Format = Format.Float3,
                Type = BufferType.InputOutput
            };

            var sampBuffDesc = new BufferDesc
            {
                Width = outputBuffer.Width,
                Height = outputBuffer.Height,
                Depth = outputBuffer.Depth,
                Format = Format.UInt,
                Type = BufferType.InputOutput
            };
            hdrBuffer = new Buffer(optixContext, spdBuffDesc);
            hdrBuffer.SetData(new Vector3[spdBuffDesc.Width * spdBuffDesc.Height]);
        }
Exemple #24
0
        void createPipelineState(IRenderDevice device)
        {
            PipelineStateDesc PSODesc = new PipelineStateDesc(false);

            PSODesc.setBufferFormats(context);

            // Primitive topology defines what kind of primitives will be rendered by this pipeline state
            PSODesc.GraphicsPipeline.PrimitiveTopology = PrimitiveTopology.TriangleList;
            // Cull back faces
            PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CullMode.Back;
            // Enable depth testing
            PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = true;

            iShaderFactory shaderFactory = device.GetShaderFactory();

            // We won't be using the device object after this, `using` is to release the COM interface once finished
            using (iPipelineStateFactory stateFactory = device.CreatePipelineStateFactory())
            {
                stateFactory.setName("Cube PSO");

                // Compile the two shaders
                ShaderSourceInfo sourceInfo = new ShaderSourceInfo(ShaderType.Vertex, ShaderSourceLanguage.Hlsl);
                sourceInfo.combinedTextureSamplers = true;                  // This appears to be the requirement of OpenGL backend.

                // In this tutorial, we will load shaders from resources embedded into this .NET DLL.
                iStorageFolder resources = StorageFolder.embeddedResources(Assembly.GetExecutingAssembly(), "RenderSamples/02-Cube");
                var            vs        = shaderFactory.compileFromFile(resources, "cube.vsh", sourceInfo, "Cube VS");
                stateFactory.graphicsVertexShader(vs);

                // Create dynamic uniform buffer that will store our transformation matrix. Dynamic buffers can be frequently updated by the CPU.
                BufferDesc CBDesc = new BufferDesc(false);
                CBDesc.uiSizeInBytes  = Marshal.SizeOf <Matrix4x4>();
                CBDesc.Usage          = Usage.Dynamic;
                CBDesc.BindFlags      = BindFlags.UniformBuffer;
                CBDesc.CPUAccessFlags = CpuAccessFlags.Write;
                vsConstants           = device.CreateBuffer(CBDesc, "VS constants CB");

                // Create a pixel shader
                sourceInfo.shaderType = ShaderType.Pixel;

                var ps = shaderFactory.compileFromFile(resources, "cube.psh", sourceInfo, "Cube PS");
                stateFactory.graphicsPixelShader(ps);

                // Define vertex shader input layout

                // Attribute 0 - vertex position
                LayoutElement elt = new LayoutElement(false)
                {
                    InputIndex    = 0,
                    BufferSlot    = 0,
                    NumComponents = 3,
                    ValueType     = GpuValueType.Float32,
                    IsNormalized  = false
                };
                stateFactory.graphicsLayoutElement(elt);
                // Attribute 1 - vertex color
                elt.InputIndex    = 1;
                elt.NumComponents = 4;
                stateFactory.graphicsLayoutElement(elt);

                // Define variable type that will be used by default
                PSODesc.ResourceLayout.DefaultVariableType = ShaderResourceVariableType.Static;

                stateFactory.apply(ref PSODesc);
                pipelineState = device.CreatePipelineState(ref PSODesc);
            }

            // Since we did not explicitly specify the type for 'Constants' variable, default
            // type (SHADER_RESOURCE_VARIABLE_TYPE_STATIC) will be used. Static variables never
            // change and are bound directly through the pipeline state object.
            pipelineState.GetStaticVariableByName(ShaderType.Vertex, "Constants").Set(vsConstants);

            // Create a shader resource binding object and bind all static resources in it
            resourceBinding = pipelineState.CreateShaderResourceBinding(true);
        }
Exemple #25
0
        /// <summary>
        /// 3Dテクスチャの初期化
        /// </summary>
        /// <param name="desc"></param>
        public void Initialize3D(BufferDesc desc)
        {
            var device = GraphicsCore.D3D11Device;

            // 情報取得
            width_  = desc.width;
            height_ = desc.height;
            format_ = desc.format;
            mips_   = desc.mips;
            if (mips_ == 0)
            {
                mips_ = 1;
            }

            BindFlags bindFlags = BindFlags.ShaderResource;

            if (desc.IsRenderTarget)
            {
                bindFlags |= BindFlags.RenderTarget;
            }
            if (desc.IsUnorderedAccess)
            {
                bindFlags |= BindFlags.UnorderedAccess;
            }
            CpuAccessFlags acc_flag  = CpuAccessFlags.None;
            ResourceUsage  res_usage = ResourceUsage.Default;

            // 初期化データ
            DataBox databox = null;

            if (desc.initData != null)
            {
                int        size = desc.initData.Length * desc.initData[0].Length * desc.initData[0][0].Length;
                DataStream s    = new DataStream(size, true, true);
                foreach (var z in desc.initData)
                {
                    foreach (var y in z)
                    {
                        s.Write(y, 0, y.Length);
                    }
                }
                databox = new DataBox(desc.width, desc.width * desc.height, s);
            }
            if (desc.initStream != null)
            {
                int bpp = (int)desc.initStream.Length / (desc.width * desc.height * desc.depth);
                desc.initStream.Position = 0;
                databox = new DataBox(desc.width * bpp, desc.width * desc.height * bpp, desc.initStream);
            }

            // テクスチャオブジェクト
            Texture3DDescription textureDescription = new Texture3DDescription {
                BindFlags      = bindFlags,
                CpuAccessFlags = acc_flag,
                Format         = desc.format,
                Height         = desc.height,
                Width          = desc.width,
                Depth          = desc.depth,
                MipLevels      = mips_,
                OptionFlags    = desc.optionFlags,
                Usage          = res_usage
            };
            var texture3d = new Texture3D(device, textureDescription, databox);

            buffer_ = texture3d;

            // 初期データ解放
            if (databox != null)
            {
                databox.Data.Close();
            }

            Format srvFormat = desc.format;
            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription {
                ArraySize       = 0,
                Format          = srvFormat,
                Dimension       = ShaderResourceViewDimension.Texture3D,
                Flags           = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels       = mips_
            };

            shaderResourceView_ = new ShaderResourceView(device, texture3d, srvViewDesc);

            // レンダーターゲットビュー
            if (desc.IsRenderTarget)
            {
                renderTargetView_ = new RenderTargetView(device, texture3d);
            }
            // UAV
            if (desc.IsUnorderedAccess)
            {
                unorderedAccessView_ = new UnorderedAccessView(device, texture3d);
            }
        }
        private void BuildGeometry(SceneMeshData SceneData, SceneMeshEntity[] sceneMesh, bool hasAreaLights = false, IEnumerable<SceneLightsource> areaLights = null)
        {
            topObject = new GeometryGroup(Session.OptixContext);
            Session.OptixContext["scene_sphere_radius"].Set(SceneData.BoundingSphereRadius);
            Session.OptixContext["scene_sphere_center"].SetFloat3(SceneData.BoundingSphereCenter);

            var vDesc = new BufferDesc { Width = (uint)SceneData.Positions.Count, Format = Format.Float3, Type = BufferType.Input };
            var nDesc = new BufferDesc { Width = (uint)SceneData.Normals.Count, Format = Format.Float3, Type = BufferType.Input };
            var tcDesc = new BufferDesc { Width = (uint)SceneData.TexCoords.Count, Format = Format.Float2, Type = BufferType.Input };

            var vBuffer = new Buffer(Session.OptixContext, vDesc);
            var nBuffer = new Buffer(Session.OptixContext, nDesc);
            var tcBuffer = new Buffer(Session.OptixContext, tcDesc);

            vBuffer.SetData(SceneData.Positions.ToArray());
            nBuffer.SetData(SceneData.Normals.ToArray());
            tcBuffer.SetData(SceneData.TexCoords.ToArray());

            var lightTriangleIndexes = new Dictionary<string, List<int>>(StringComparer.InvariantCultureIgnoreCase);

            var instances = new List<GeometryInstance>();
            var triLights = new List<TriangleLight>();
            int idx = 0;
            foreach (var group in sceneMesh)
            {
                //empty group

                if (group.VertexIndexes.Count == 0 && group.NormalIndexes.Count == 0 && group.TextureIndexes.Count == 0)
                    continue;

                var center = new Vector3();
                foreach (var vi in group.VertexIndexes)
                {
                    center += SceneData.Positions[vi.X];
                    center += SceneData.Positions[vi.Y];
                    center += SceneData.Positions[vi.Z];
                    center /= 3.0f;
                }
                //ValidateGroup( group );

                //var mat = this.ResolveMaterial(group.Material);

                bool normalsUseVIndices = GenerateNormals && group.NormalIndexes.Count == 0 && SceneData.Normals.Count > 0;

                if (normalsUseVIndices)
                    Debug.Assert(SceneData.Normals.Count == SceneData.Positions.Count);

                int numNormIndices = normalsUseVIndices ? group.VertexIndexes.Count : group.NormalIndexes.Count;

                var viDesc = new BufferDesc() { Width = (uint)group.VertexIndexes.Count, Format = Format.Int3, Type = BufferType.Input };
                var niDesc = new BufferDesc() { Width = (uint)numNormIndices, Format = Format.Int3, Type = BufferType.Input };
                var tiDesc = new BufferDesc() { Width = (uint)group.TextureIndexes.Count, Format = Format.Int3, Type = BufferType.Input };

                var viBuffer = new Buffer(Session.OptixContext, viDesc);
                var niBuffer = new Buffer(Session.OptixContext, niDesc);
                var tiBuffer = new Buffer(Session.OptixContext, tiDesc);

                viBuffer.SetData(group.VertexIndexes.ToArray());
                niBuffer.SetData(normalsUseVIndices ? group.VertexIndexes.ToArray() : group.NormalIndexes.ToArray());
                tiBuffer.SetData(group.TextureIndexes.ToArray());

                var geometry = new Geometry(Session.OptixContext);
                string intersect_program = "mesh_intersect";
                string isect_script = IntersectionScript;
                //if (!string.IsNullOrWhiteSpace(group.mtrl) && matTypes.ContainsKey(group.mtrl))
                //{
                //    if (matTypes[group.mtrl].Equals("Volume"))
                //    {
                //        intersect_program = "volume_mesh_intersect";
                //        isect_script = GetScript("triangle_mesh_iterative.ptx");
                //    }
                //}

                geometry.IntersectionProgram = new Program(Session.OptixContext, isect_script, intersect_program);
                geometry.BoundingBoxProgram = new Program(Session.OptixContext, isect_script, "mesh_bounds");
                geometry.PrimitiveCount = (uint)group.VertexIndexes.Count;

                geometry["vertex_buffer"].Set(vBuffer);
                geometry["normal_buffer"].Set(nBuffer);
                geometry["texcoord_buffer"].Set(tcBuffer);
                geometry["vindex_buffer"].Set(viBuffer);
                geometry["nindex_buffer"].Set(niBuffer);
                geometry["tindex_buffer"].Set(tiBuffer);

                var instance = new GeometryInstance(Session.OptixContext);
                instance.Geometry = geometry;
                instance["geometric_center"].SetFloat3(center);
                //instance.AddMaterial(mat);
                group.EngineEntity = geometry;
                if (group.Material != null)
                {
                    int lindex;
                    if (hasAreaLights && MeshIsLight(group.Name, out lindex))
                    {
                        instance.AddMaterial(this.GetLightMaterial(group.Material, lindex));
                    }
                    else
                    {
                        var mtrl = ResolveMaterial(group.Material);

                        if (mtrl != null)
                        {
                            group.Material.EngineEntity = mtrl;
                            instance.AddMaterial(mtrl);
                            SetDefaultMaterialProperties(instance, mtrl, group.Material);
                        }
                        else
                        {
                            Tracer.WriteLine("Mesh {0} missed material {1}", group.Name, group.Material.Name);
                        }
                    }
                }
                else
                {
                    Tracer.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ----Mesh {0} missed material {1}", group.Name, group.Material);
                    Console.ReadLine();
                }

                //if (!string.IsNullOrWhiteSpace(LightNameTemplate))
                //{
                //    Regex lightReg = new Regex(LightNameTemplate, RegexOptions.IgnoreCase);

                //    if (lightReg.IsMatch(group.Name))
                //    {
                //        var lt = new Lightsource()
                //        {
                //            Type = LightSourceTypes.Area,
                //            Emission = Scene.LightGain,
                //            Name = group.Name,
                //        };
                //        lt[Lightsource.AreaMeshName] = group.Name;
                //        Scene.Lights = Scene.Lights.Union(new[] { lt }).ToArray();
                //    }
                //}

                if (hasAreaLights)
                {
                    var light =
                        areaLights.FirstOrDefault(
                            lt => lt.Name.Equals(group.Name, StringComparison.InvariantCultureIgnoreCase));
                    //    SetDefaultLightProperties(instance, light);

                    if (light != null)
                    {
                        var ti = new List<int>();
                        lightTriangleIndexes.Add(group.Name, ti);
                        for (int index = 0; index < group.VertexIndexes.Count; index++)
                        {
                            var vIndex = group.VertexIndexes[index];
                            var v1 = SceneData.Positions[vIndex.X];
                            var v2 = SceneData.Positions[vIndex.Y];
                            var v3 = SceneData.Positions[vIndex.Z];
                            var e1 = v2 - v3;
                            var e2 = v1 - v3;
                            Vector3 n = Vector3.Cross(ref e1, ref e2);//SceneGraph.LightOrientation *
                            if (group.NormalIndexes.Any())
                            {
                                n = (SceneData.Normals[group.NormalIndexes[index].X]);//Scene.LightOrientation *
                            }

                            n.Normalize();
                            ti.Add(idx + 1);
                            triLights.Add(new TriangleLight()
                            {
                                color = light.Color, //Emission * emissionScale,
                                v1 = v1,
                                v2 = v2,
                                v3 = v3,
                                normal = n,
                                idx = idx++
                            });
                        }
                    }
                }
                instances.Add(instance);
            }

            var Builder = AccelBuilder.Sbvh;
            var Traverser = AccelTraverser.Bvh;

            //create an acceleration structure for the geometry
            var accel = new Acceleration(Session.OptixContext, Builder, Traverser);

            if (Builder == AccelBuilder.Sbvh || Builder == AccelBuilder.TriangleKdTree)
            {
                accel.VertexBufferName = "vertex_buffer";
                accel.IndexBufferName = "vindex_buffer";
            }

            //now attach the instance and accel to the geometry group
            topObject.Acceleration = accel;
            topObject.AddChildren(instances);
            topObject.Acceleration.MarkAsDirty();
            BuildCache.Add("LightTrianglesIndexes", lightTriangleIndexes);
            BuildCache.Add("LightTriangles", triLights);
        }
Exemple #27
0
        protected override void Initialize()
        {
            string rayGenPath = shaderPath;

            /*-----------------------------------------------
             * Create the Optix context
             *-----------------------------------------------*/
            OptixContext = new Context();
            OptixContext.RayTypeCount    = 2;
            OptixContext.EntryPointCount = 1;
            OptixContext.SetStackSize(4096);

            /* Create the ray-generation and exception programs
             *-----------------------------------------------*/
            var rayGen    = new OptixProgram(OptixContext, rayGenPath, mTutorial < 11 ? "pinhole_camera" : "env_camera");
            var exception = new OptixProgram(OptixContext, rayGenPath, "exception");
            var miss      = new OptixProgram(OptixContext, rayGenPath, mTutorial < 5 ? "miss" : "envmap_miss");

            OptixContext["bg_color"].Set(100 / 255.0f, 149 / 255.0f, 237 / 255.0f);
            OptixContext["bad_color"].Set(1.0f, 0.0f, 0.0f);

            OptixContext.SetRayGenerationProgram(0, rayGen);
            OptixContext.SetExceptionProgram(0, exception);
            OptixContext.SetRayMissProgram(0, miss);

            /*-----------------------------------------------
             * Create lights
             *-----------------------------------------------*/
            BasicLight[] lights = new BasicLight[1];
            lights[0].Position    = new Vector3(-5.0f, 60.0f, -16.0f);
            lights[0].Color       = new Vector3(1.0f, 1.0f, 1.0f);
            lights[0].CastsShadow = 1;

            BufferDesc desc = new BufferDesc()
            {
                Width    = (uint)lights.Length,
                Format   = Format.User,
                Type     = BufferType.Input,
                ElemSize = (uint)Marshal.SizeOf(typeof(BasicLight))
            };
            Buffer lightsBuffer = new Buffer(OptixContext, desc);

            lightsBuffer.SetData <BasicLight>(lights);

            OptixContext["lights"].Set(lightsBuffer);

            /*-----------------------------------------------
             * Create noise texture
             *-----------------------------------------------*/
            if (mTutorial >= 8)
            {
                uint noiseTexDim = 64;
                desc = new BufferDesc()
                {
                    Width = noiseTexDim, Height = noiseTexDim, Depth = noiseTexDim, Format = Format.Float, Type = BufferType.Input
                };
                Buffer noiseBuffer = new Buffer(OptixContext, desc);

                Random       rand   = new Random();
                BufferStream stream = noiseBuffer.Map();
                for (int i = 0; i < noiseTexDim * noiseTexDim * noiseTexDim; i++)
                {
                    stream.Write <float>((float)rand.NextDouble());
                }
                noiseBuffer.Unmap();

                TextureSampler noiseTex = new TextureSampler(OptixContext, TextureSamplerDesc.GetDefault(WrapMode.Repeat));
                noiseTex.SetBuffer(noiseBuffer);

                OptixContext["noise_texture"].Set(noiseTex);
            }

            /*-----------------------------------------------
             * Load enivronment map texture
             *-----------------------------------------------*/
            LoadEnvMap();

            /*-----------------------------------------------
             * Load the geometry
             *-----------------------------------------------*/
            CreateGeometry();

            /*-----------------------------------------------
             * Create the output buffer
             *-----------------------------------------------*/
            CreateOutputBuffer(Format.UByte4);
            OptixContext["output_buffer"].Set(OutputBuffer);

            /*-----------------------------------------------
             * Finally compile the optix context, and build the accel tree
             *-----------------------------------------------*/
            SetCamera();

            OptixContext["max_depth"].Set(100);
            OptixContext["radiance_ray_type"].Set(0u);
            OptixContext["shadow_ray_type"].Set(1u);
            OptixContext["frame_number"].Set(0u);
            OptixContext["scene_epsilon"].Set(.001f);
            OptixContext["importance_cutoff"].Set(0.01f);
            OptixContext["ambient_light_color"].Set(0.31f, 0.33f, 0.28f);

            OptixContext.Compile();
            OptixContext.BuildAccelTree();

            //very loose calculation of number of rays
            float numSecondaryRays = 0;

            if (mTutorial >= 9)
            {
                numSecondaryRays = 2.5f; //only convex hull casts refraction rays
            }
            else if (mTutorial >= 8)
            {
                numSecondaryRays = 2;
            }
            else if (mTutorial >= 4)
            {
                numSecondaryRays = 1.5f; //only the floor casts reflection rays, so give aproximate
            }
            else if (mTutorial >= 3)
            {
                numSecondaryRays = 1;
            }

            RaysTracedPerFrame = (int)(Width * Height * (numSecondaryRays + 1));
        }
        protected override void CreateGeometry()
        {
            base.CreateGeometry();

            if (!GenerateGeometry)
            {
                return;
            }

            //create buffer descriptions
            var vDesc = new BufferDesc()
            {
                Width = (uint)Positions.Count, Format = Format.Float3, Type = BufferType.Input
            };
            var nDesc = new BufferDesc()
            {
                Width = (uint)Normals.Count, Format = Format.Float3, Type = BufferType.Input
            };
            var tcDesc = new BufferDesc()
            {
                Width = (uint)Texcoords.Count, Format = Format.Float2, Type = BufferType.Input
            };

            // Create the buffers to hold our geometry data
            var vBuffer  = new OptixBuffer(Context, vDesc);
            var nBuffer  = new OptixBuffer(Context, nDesc);
            var tcBuffer = new OptixBuffer(Context, tcDesc);

            vBuffer.SetData <Vector3>(Positions.ToArray());
            nBuffer.SetData <Vector3>(Normals.ToArray());
            tcBuffer.SetData <Vector2>(Texcoords.ToArray());

            List <GeometryInstance> instances = new List <GeometryInstance>();

            foreach (ObjGroup group in Groups)
            {
                //empty group
                if (group.VIndices.Count == 0 && group.NIndices.Count == 0 && group.TIndices.Count == 0)
                {
                    continue;
                }

                //ValidateGroup( group );

                var normalsUseVIndices = GenerateNormals && group.NIndices.Count == 0 && Normals.Count > 0;

                if (normalsUseVIndices)
                {
                    Debug.Assert(Normals.Count == Positions.Count);
                }

                var numNormIndices = normalsUseVIndices ? group.VIndices.Count : group.NIndices.Count;

                var viDesc = new BufferDesc {
                    Width = (uint)group.VIndices.Count, Format = Format.Int3, Type = BufferType.Input
                };
                var niDesc = new BufferDesc {
                    Width = (uint)numNormIndices, Format = Format.Int3, Type = BufferType.Input
                };
                var tiDesc = new BufferDesc {
                    Width = (uint)group.TIndices.Count, Format = Format.Int3, Type = BufferType.Input
                };

                var viBuffer = new OptixBuffer(Context, viDesc);
                var niBuffer = new OptixBuffer(Context, niDesc);
                var tiBuffer = new OptixBuffer(Context, tiDesc);

                viBuffer.SetData(group.VIndices.ToArray());
                //if normals weren't in the obj and we genereated them, use the vertex indices
                niBuffer.SetData(normalsUseVIndices ? group.VIndices.ToArray() : group.NIndices.ToArray());
                tiBuffer.SetData(group.TIndices.ToArray());

                //create a geometry node and set the buffers
                var geometry = new Geometry(Context);
                geometry.IntersectionProgram = new OptixProgram(Context, IntersecitonProgPath, IntersecitonProgName);
                geometry.BoundingBoxProgram  = new OptixProgram(Context, BoundingBoxProgPath, BoundingBoxProgName);
                geometry.PrimitiveCount      = (uint)group.VIndices.Count;

                geometry["vertex_buffer"].Set(vBuffer);
                geometry["normal_buffer"].Set(nBuffer);
                geometry["texcoord_buffer"].Set(tcBuffer);
                geometry["vindex_buffer"].Set(viBuffer);
                geometry["nindex_buffer"].Set(niBuffer);
                geometry["tindex_buffer"].Set(tiBuffer);

                //create a geometry instance
                GeometryInstance instance = new GeometryInstance(Context);
                instance.Geometry = geometry;
                instance.AddMaterial(_materialResolveFunc(group.mtrl) ?? DefaultMaterial);

                if (group.mtrl != null)
                {
                    ObjMaterial mtrl = mMtrls[group.mtrl];
                    instance["diffuse_color"].SetFloat3(ref mtrl.Kd);
                    instance["emission_color"].SetFloat3(ref mtrl.Ke);
                }
                else
                {
                    instance["diffuse_color"].Set(1.0f, 1.0f, 1.0f);
                }

                instances.Add(instance);
            }

            //create an acceleration structure for the geometry
            var accel = new Acceleration(Context, Builder, Traverser);

            if (Builder == AccelBuilder.Sbvh || Builder == AccelBuilder.TriangleKdTree)
            {
                accel.VertexBufferName = "vertex_buffer";
                accel.IndexBufferName  = "vindex_buffer";
            }

            //now attach the instance and accel to the geometry group
            GeoGroup.Acceleration = accel;
            GeoGroup.AddChildren(instances);
        }
        public override void Initialize(Action<BoundingBox> setCamera, params object[] parameters)
        {
            string rayGenPath = PtxDir + ("spectral_path_tracer.cu.ptx");
            string shaderPath = PtxDir + ("spectral_materials.cu.ptx");

            var objFileName = parameters[0] as string;

            if (base.Context == null)
            {
                this.CreateContext();
            }

            var Context = base.Context;
            var Width = (int)parameters[1];
            var Height = (int)parameters[2];

            var desc = new BufferDesc()
            {
                Width = (uint)Width,
                Height = (uint)Height,
                Format = Format.Float3,
                Type = BufferType.InputOutput
            };

            var hdrBuffer = new OptixDotNet.Buffer(Context, desc);
            Context["hdr_buffer"].Set(hdrBuffer);

            Context["Y_log_av"].Set(yAvg);
            // maximum luminance
            Context["Y_max"].Set(yMax);

            Context["sig_e"].SetFloat3(new Vector3(0.7f, 0.7f, 0.7f));
            Context["sig_a"].SetFloat3(new Vector3(0.1f, 0.3f, 0.1f));

            /*-----------------------------------------------
             * Create the material that will be executed when there is an intersection
             *-----------------------------------------------*/

            Material material = new Material(Context);
            material.Programs[0] = new SurfaceProgram(Context, RayHitType.Closest, shaderPath, "diffuse_all"); //glass_refract,diffuse
            material.Programs[1] = new SurfaceProgram(Context, RayHitType.Any, shaderPath, "shadow");


            /*-----------------------------------------------
             * Create the output buffer
             *-----------------------------------------------*/



            /*-----------------------------------------------
             * Create the ray-generation and exception programs
             *-----------------------------------------------*/
            Program rayGen = new Program(Context, rayGenPath, "pathtrace_camera");
            Program exception = new Program(Context, rayGenPath, "exception");
            Program miss = new Program(Context, shaderPath, "miss");
            Context["use_envmap"].Set(0u);

            Context.SetRayMissProgram(0, miss);
            Context.SetRayGenerationProgram(0, rayGen);

            miss["bg_color"].Set(1f,1f,0f);

            Context.SetExceptionProgram(0, exception);

            /*-----------------------------------------------
             * Finally compile the optix context, and build the accel tree
             *-----------------------------------------------*/
            setCamera(Scene.BBox);
            //skyModel._up = this.Camera.Up;

            //skyModel.InitContext(Context);
            Context["directional_light"].SetFloat3(skyModel._sun_dir * 100000f);
            Context["directional_light_col"].SetFloat3(skyModel._sun_color * (1.0f / 1600000.0f));
            Context["directional_light_col"].SetFloat3(skyModel._sun_color * (1.0f / 1600000.0f));
            //Context["emission_color"].SetFloat3(skyModel._sun_color * (1.0f / 1600000.0f));
            Context["emission_color"].SetFloat3(new Vector3(0,0,0));


            Context["top_object"].Set(this.sceneManager.Scene.TopObject);
            Context["output_buffer"].Set(OutputBuffer);
            Context["scene_epsilon"].Set(this.SceneEpsilon);


            Context["rr_begin_depth"].Set(rrBeginDepth);
            Context["max_depth"].Set(maxDepth);

            Context["sqrt_num_samples"].Set(sqrtSamples);
            Context["frame_number"].Set(mFrame);

            Context["pathtrace_ray_type"].Set(0u);
            Context["pathtrace_shadow_ray_type"].Set(1u);
            Context["glass_color"].SetFloat3(new Vector3(0.50f, 0.50f, 0.50f));
            Context["diffuse_color"].SetFloat3(new Vector3(0.50f, 0.50f, 0.50f));
            Context["shadow_attenuation"].SetFloat3(new Vector3());
            Context["extinction_constant"].SetFloat3(new Vector3() + 0.75f);


            Context["index_of_refraction"].Set(1.7f);
            Context["focal_scale"].Set(0.0f);
            Context["aperture_radius"].Set(apertureSize);



            Context["bad_color"].SetFloat3(new Vector3(1.0f, 1.0f, 0.0f));

            Console.Write("Compiling Optix... ");
            float start = Time.GetTimeInSecs();
            //if (!LoadAccelData(model, modelPath, accelCache)) {
            //    model.GeoGroup.Acceleration.MarkAsDirty();
            //}

            // bool accelIsDirty = model.GeoGroup.Acceleration.IsDirty();

            Context.Compile();

            Context.BuildAccelTree();

            Console.WriteLine("{0:0.00}s", Time.GetTimeInSecs() - start);
        }
        private void CreateLights(IEnumerable<TriangleLight> lights)
        {

            BufferDesc desc = new BufferDesc() { Width = (uint)(lights.Count()), Format = Format.User, Type = BufferType.Input, ElemSize = (uint)Marshal.SizeOf(typeof(TriangleLight)) };
            OptixDotNet.Buffer lightBuffer = new OptixDotNet.Buffer(Context, desc);
            BufferStream stream = lightBuffer.Map();
            {
                foreach (var triangleLight in lights)
                {
                    triangleLight.normal.Normalize();
                    stream.Write(triangleLight);
                }
            }
            lightBuffer.Unmap();

            Context["lights"].Set(lightBuffer);
        }
        public override void SetScene(IRayEngineScene secn)
        {
            string shaderPath = Path.GetFullPath(@"G:\Git\RayDen\RayDen.OptixEngine\Cuda\Scripts\CudaScripts\hitkernel.ptx");

            Tracer.TraceLine("OptixIntersectionDevice  -  Initializing Optix");
            this.scene = (RayEngineScene) secn;
            var scn = scene.SceneGeometry;

            Material material = new Material(Context);
            material.Programs[0] = new SurfaceProgram(Context, RayHitType.Closest, shaderPath, "first_hit");
            //            material.Programs[1] = new SurfaceProgram(Context, RayHitType.Any, shaderPath, "shadow");


            var mVertices = scn.Vertices.ToList();
            var mNormals = scn.Normals.ToList();
            List<UV> mTexcoords = null;
            mTexcoords = scn.TexCoords == null ? new List<UV>() : scn.TexCoords.Select(it=>new UV(it.x,it.y)).ToList();

            var vDesc = new BufferDesc() { Width = (uint)mVertices.Count, Format = Format.Float3, Type = BufferType.Input };
            var nDesc = new BufferDesc() { Width = (uint)mNormals.Count, Format = Format.Float3, Type = BufferType.Input };
            var tcDesc = new BufferDesc() { Width = (uint)mTexcoords.Count, Format = Format.Float2, Type = BufferType.Input };

            // Create the buffers to hold our geometry data
            var vBuffer = new  DeviceBuffer(Context, vDesc);
            var nBuffer = new  DeviceBuffer(Context, nDesc);
            var tcBuffer = new DeviceBuffer(Context, tcDesc);


            vBuffer.SetData(mVertices.ToArray());
            nBuffer.SetData(mNormals.ToArray());
            tcBuffer.SetData(mTexcoords.ToArray());


            foreach (var triangleMesh in scene.Meshes.Cast<TriangleMeshInfo>())
            {
                var group = triangleMesh;


                var viDesc = new BufferDesc() { Width = (uint)(group.TrianglesCount), Format = Format.Int3, Type = BufferType.Input };
                var niDesc = new BufferDesc() { Width = (uint)(group.TrianglesCount), Format = Format.Int3, Type = BufferType.Input };
                var tiDesc = new BufferDesc() { Width = (uint)(group.TrianglesCount), Format = Format.Int3, Type = BufferType.Input };
                var ofsDesc = new BufferDesc()
                    {
                        Width = (uint) (group.TrianglesCount),
                        Format = Format.UInt,
                        Type = BufferType.Input
                    };

                var viBuffer = new DeviceBuffer(Context, viDesc);
                var niBuffer = new DeviceBuffer(Context, niDesc);
                var tiBuffer = new DeviceBuffer(Context, tiDesc);

                var gIndexes =
                    scene.Triangles.ToList().GetRange(group.StartTriangle, group.TrianglesCount)
                         .SelectMany(tri => new []
                             {
                                 tri.v0.VertexIndex,
                                 tri.v1.VertexIndex,
                                 tri.v2.VertexIndex
                             })
                         .ToArray();

                var gNIndexes =
                    scene.Triangles.ToList().GetRange(group.StartTriangle, group.TrianglesCount)
                         .SelectMany(tri => new[]
                             {
                                 tri.v0.NormalIndex,
                                 tri.v1.NormalIndex,
                                 tri.v2.NormalIndex
                             })
                         .ToArray();
                var gTIndexes =
                    scene.Triangles.ToList().GetRange(group.StartTriangle, group.TrianglesCount)
                         .SelectMany(tri => new []
                             {
                                 tri.v0.TexCoordIndex,
                                 tri.v1.TexCoordIndex,
                                 tri.v2.TexCoordIndex
                             })
                         .ToArray();

                viBuffer.SetData(Convert(gIndexes).ToArray());
                niBuffer.SetData(Convert(gNIndexes).ToArray());
                tiBuffer.SetData(Convert(gTIndexes).ToArray());

                var geometry = new Geometry(Context);
                geometry.IntersectionProgram = new Program(Context, IntersecitonProgPath, IntersecitonProgName);
                geometry.BoundingBoxProgram = new Program(Context, BoundingBoxProgPath, BoundingBoxProgName);
                geometry.PrimitiveCount = (uint)(group.EndTriangle - group.StartTriangle);

                geometry["vertex_buffer"].Set(vBuffer);
                geometry["normal_buffer"].Set(nBuffer);
                geometry["texcoord_buffer"].Set(tcBuffer);
                geometry["vindex_buffer"].Set(viBuffer);
                geometry["nindex_buffer"].Set(niBuffer);
                geometry["tindex_buffer"].Set(tiBuffer);
                geometry["mesh_offset"].SetInt4(group.StartTriangle);
                //geometry[ "material_buffer" ].Set(mtBuffer);

                //create a geometry instance
                var instance = new GeometryInstance(Context);
                instance.Geometry = geometry;
                instance.AddMaterial(material);
                //create an acceleration structure for the geometry
                Acceleration accel = new Acceleration(Context, Builder, Traverser);

                if (Builder == AccelBuilder.Sbvh || Builder == AccelBuilder.TriangleKdTree)
                {
                    accel.VertexBufferName = "vertex_buffer";
                    accel.IndexBufferName = "vindex_buffer";
                }

                //now attach the instance and accel to the geometry group
                GeoGroup.Acceleration = accel;
                GeoGroup.AddChildren(new[] { instance });
            }

            Program rayGen = new Program(Context, shaderPath, "intersector_camera");
            Program exception = new Program(Context, shaderPath, "exception");
            Program miss = new Program(Context, shaderPath, "miss");
            Context["intersect_ray_type"].Set(0u);
            Context["scene_epsilon"].Set(0.0001f);
            Context.SetRayGenerationProgram(0, rayGen);
            Context.SetExceptionProgram(0, exception);
            Context.SetRayMissProgram(0, miss);
            Context["top_object"].Set(GeoGroup);
            Tracer.TraceLine("OptixIntersectionDevice  -  Compiling Optix contex");
            Context.Compile();
            Context.BuildAccelTree();
            Tracer.TraceLine("OptixIntersectionDevice  -  Complete");
        }
Exemple #32
0
        public TextureSampler CreateTextureSampler(string path, bool scale = false)
        {
            var newTex = Path.GetFileName(path) ?? path;
            if (samplers.ContainsKey(newTex))
                return samplers[newTex];
            else
            {
                if (!File.Exists(path))
                {
                    Console.WriteLine("ISSUES DUDE {0} not found", path);
                    throw new ArgumentException("imagepath");
                }
                Console.WriteLine("{0} Loading. {1} total samplers loaded ", Path.GetFileName(path), samplers.Count);
                using (var bitmap = new FreeImageBitmap(path))
                {
                    var bmp = bitmap.Width > MaxTextureWidth || bitmap.Height > MaxTextureHeight
                        ? GetScaledBmp(bitmap)
                        : bitmap;
                    var desc = new BufferDesc()
                    {
                        Width = (uint) bmp.Width,
                        Height = (uint) bmp.Height,
                        Format = Format.Float4,
                        Type = BufferType.Input
                    };
                    var texData = EngineContext.Instance.ResourceManager.CreateBuffer(context, desc);

                    BufferStream data = texData.Map();
                    for (int i = 0; i < bmp.Height; i++)
                    {

                        switch (bmp.ColorDepth)
                        {

                            case 8:
                                Scanline<byte> s_8 = bmp.GetScanline<byte>(i);

                                for (int j = 0; j < bmp.Width; j++)
                                {
                                    var c = new Vector4(bmp.Palette[s_8[j]].rgbRed/255.0f,
                                        bmp.Palette[s_8[j]].rgbGreen/255.0f,
                                        bmp.Palette[s_8[j]].rgbBlue/255.0f,
                                        1.0f);
                                    data.Write(c);

                                }
                                break;

                            case 24:
                                Scanline<RGBTRIPLE> s_t = bmp.GetScanline<RGBTRIPLE>(i);
                                for (int j = 0; j < bmp.Width; j++)
                                {
                                    var rgb =
                                        new RgbSpectrum(s_t[j].rgbtRed/255.0f, s_t[j].rgbtGreen/255.0f,
                                            s_t[j].rgbtBlue/255.0f);
                                    rgb.DeGamma();
                                    var c = new Vector4(rgb.c1, rgb.c2, rgb.c3, 1.0f);
                                    data.Write(c);

                                }
                                break;

                            case 32:
                                Scanline<RGBQUAD> s_32 = bmp.GetScanline<RGBQUAD>(i);
                                for (int j = 0; j < bmp.Width; j++)
                                {
                                    var rgb =
                                        new RgbSpectrum(s_32[j].rgbRed / 255.0f,
                                                        s_32[j].rgbGreen / 255.0f,
                                                        s_32[j].rgbBlue / 255.0f);
                                    rgb.DeGamma();
                                    var c = new Vector4(rgb.c1, rgb.c2, rgb.c3, 1.0f);

                                    data.Write(c);

                                }
                                break;


                        }


                    }

                    texData.Unmap();

                    TextureSamplerDesc texDesc = TextureSamplerDesc.Default;
                    texDesc.Read = TextureReadMode.ElementType;
                    TextureSampler sampler = new TextureSampler(context, texDesc);
                    sampler.SetBuffer(texData, 0);
                    samplers.Add(newTex, sampler);
                    Console.WriteLine("2D Sampler loaded  {0} {1}x{2} pixels", path, bmp.Width, bmp.Height);
                    return sampler;
                }
            }
        }
        private void BuildLights(SceneLightsource[] sceneLights)
        {
            var lightInfos = new List<LightInfo>();
            foreach (var sceneLightsource in sceneLights)
            {
                var lightInfo = sceneLightsource.CreateInfo();
                if (lightInfo.type == 5)
                {
                    EnvMapPath = sceneLightsource.Get("EnvMap.Image", string.Empty);
                }
                if (lightInfo.type != 2)
                {
                    lightInfos.Add(lightInfo);
                }
                else
                {
                    var li = ((Dictionary<string, List<int>>)BuildCache["LightTrianglesIndexes"])[((SceneMeshEntity)sceneLightsource["AreaLight.Mesh"]).Name];
                    lightInfos.Add(new LightInfo()
                    {
                        type = 2,
                        emission = sceneLightsource.Color,
                        startTriangle = li.Min(),
                        endTriangle = li.Max(),
                    });
                }
            }

            var triangleInfos = ((List<TriangleLight>)BuildCache["LightTriangles"]).Select(tr => new LightTriangleInfo()
            {
                v0 = tr.v1,
                v1 = tr.v2,
                v2 = tr.v3,
                n = tr.normal,
                area = CalcTriangleArea(tr)
            }).ToList();

            //TODO Index from 1!!! First triangle is fake
            triangleInfos.Insert(0, new LightTriangleInfo()
            {
                area = 1,
                n = new Vector3(1, 1, 1),
                v1 = new Vector3(100, 100, 100),
                v2 = new Vector3(101, 101, 101),
                v0 = new Vector3(102, 102, 102),
            });

            var triBufferDesc = new BufferDesc
            {
                Width = (uint)triangleInfos.Count,
                Format = Format.User,
                Type = BufferType.Input,
                ElemSize = (uint)Marshal.SizeOf(typeof(LightTriangleInfo))
            };
            var triangleBuffer = new Buffer(Session.OptixContext, triBufferDesc);
            var stream = triangleBuffer.Map();
            stream.WriteRange(triangleInfos.ToArray());
            triangleBuffer.Unmap();

            if (!string.IsNullOrWhiteSpace(EnvMapPath))
            {
                Tracer.Print("BuildLights", "Loading environment map " + EnvMapPath);
                var sceneEnvMapPath = EnvMapPath;
                var envmap = TextureCache.Instance.Load(Session.OptixContext, sceneEnvMapPath); //KC_outside_hi.hdr
                var id = envmap.GetId();
                Session.OptixContext["envmapId"].Set((uint)id);
                Session.OptixContext["use_envmap"].Set(1);

                var elt = lightInfos.Find(lt => lt.type == 5);
                var index = lightInfos.IndexOf(elt);
                lightInfos[index] = new LightInfo
                {
                    type = 5,
                    samplerId = id,
                    emission = elt.emission
                };
            }
            else
            {
                Session.OptixContext["use_envmap"].Set(0);
            }

            var ltBufferDesc = new BufferDesc
            {
                Width = (uint)lightInfos.Count,
                Format = Format.User,
                Type = BufferType.Input,
                ElemSize = (uint)Marshal.SizeOf(typeof(LightInfo))
            };
            var lightBuffer = new OptixDotNet.Buffer(Session.OptixContext, ltBufferDesc);
            var ltStream = lightBuffer.Map();
            //LightsCount.LValue += lts.Count;

            foreach (var lightinfo in lightInfos)
            {
                ltStream.Write(lightinfo);
            }
            lightBuffer.Unmap();

            Session.Frame.LightTrianglesBuffer = triangleBuffer;
            Session.Frame.LightBuffer = lightBuffer;
        }
Exemple #34
0
        /// <summary>
        /// ファイルから
        /// </summary>
        /// <param name="file_name"></param>
        public TextureBuffer(string file_name)
        {
            using (var stream = new System.IO.FileStream(file_name, System.IO.FileMode.Open, FileAccess.Read)) {
                byte[] data = new byte[stream.Length];
                stream.Read(data, 0, (int)stream.Length);
                MemoryStream s = new MemoryStream(data);

                // 名前からDDSかを判別
                string ext = Path.GetExtension(file_name).ToLower();
                if (ext == ".kstex")
                {
                    // ksTex
                    // byte配列からポインタを取得
                    var         handle = GCHandle.Alloc(data, GCHandleType.Pinned);
                    IntPtr      ptr    = handle.AddrOfPinnedObject();
                    ksTexHeader header = (ksTexHeader)Marshal.PtrToStructure(ptr, typeof(ksTexHeader));
                    int         offset = Marshal.SizeOf(header);

                    // ストリームの一をセットしてSRV生成
                    s.Position          = offset;
                    shaderResourceView_ = ShaderResourceView.FromStream(GraphicsCore.D3D11Device, s, header.data_size);
                    handle.Free();
                }
                else if (ext == ".tga")
                {
                    // tga
                    var       handle     = GCHandle.Alloc(data, GCHandleType.Pinned);
                    IntPtr    ptr        = handle.AddrOfPinnedObject();
                    tgaHeader header     = (tgaHeader)Marshal.PtrToStructure(ptr, typeof(tgaHeader));
                    int       offset     = Marshal.SizeOf(header);
                    int       image_size = header.width * header.height * 4;                    // 32bit固定
                    byte[]    image_buf  = new byte[image_size];
                    // 上下反転
                    int w            = header.width;
                    int h            = header.height;
                    int dst_row_size = w * 4;
                    int bpp          = header.depth / 8;
                    int src_row_size = w * bpp;
                    Func <int, int, int> getAddrFunc;
                    if ((header.flag & (1 << 5)) == 0)
                    {
                        getAddrFunc = (height, current_heght) => {
                            return((height - 1 - current_heght) * dst_row_size);
                        };
                    }
                    else
                    {
                        getAddrFunc = (height, current_heght) => {
                            return(current_heght * dst_row_size);
                        };
                    }
                    for (int ch = 0; ch < h; ch++)
                    {
                        int src_start = src_row_size * ch + offset;
                        int dst_start = getAddrFunc(h, ch);
                        for (int cw = 0; cw < w; cw++)
                        {
                            int src = src_start + cw * bpp;
                            int dst = dst_start + cw * 4;
                            image_buf[dst + 0] = data[src + 0];
                            image_buf[dst + 1] = data[src + 1];
                            image_buf[dst + 2] = data[src + 2];
                            image_buf[dst + 3] = (bpp == 4) ? data[src + 3] : (byte)255;
                        }
                    }
                    byte[][][] data_ary = new byte[][][] {
                        new byte[][] {
                            image_buf,
                        },
                    };
                    BufferDesc desc = new BufferDesc()
                    {
                        width    = header.width,
                        height   = header.height,
                        format   = Format.B8G8R8A8_UNorm,
                        initData = data_ary,
                        mips     = 0,
                    };
                    Initialize(desc);
                    handle.Free();
                }
                else
                {
                    // その他フォーマット
                    shaderResourceView_ = ShaderResourceView.FromStream(GraphicsCore.D3D11Device, s, (int)stream.Length);
                }

                // 情報取得
                if (shaderResourceView_.Resource is Texture2D)
                {
                    var tex = (Texture2D)shaderResourceView_.Resource;
                    width_  = tex.Description.Width;
                    height_ = tex.Description.Height;
                    format_ = tex.Description.Format;
                    mips_   = tex.Description.MipLevels;
                }
                else if (shaderResourceView_.Resource is Texture3D)
                {
                    var tex = (Texture3D)shaderResourceView_.Resource;
                    width_  = tex.Description.Width;
                    height_ = tex.Description.Height;
                    format_ = tex.Description.Format;
                    mips_   = tex.Description.MipLevels;
                }

                buffer_ = shaderResourceView_.Resource;
            }
        }
Exemple #35
0
        void createPipelineState(IRenderDevice device, iStorageFolder assets)
        {
            PipelineStateDesc PSODesc = new PipelineStateDesc(false);

            PSODesc.setBufferFormats(context);

            // Primitive topology defines what kind of primitives will be rendered by this pipeline state
            PSODesc.GraphicsPipeline.PrimitiveTopology = PrimitiveTopology.TriangleList;
            // Cull back faces
            PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CullMode.Back;
            // Enable depth testing
            PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = true;

            iShaderFactory shaderFactory = device.GetShaderFactory();

            // We won't be using the factory object after this, `using` to release the COM interface once finished
            using (iPipelineStateFactory stateFactory = device.CreatePipelineStateFactory())
            {
                stateFactory.setName("Cube PSO");

                // Compile the two shaders
                ShaderSourceInfo sourceInfo = new ShaderSourceInfo(ShaderType.Vertex, ShaderSourceLanguage.Hlsl);
                sourceInfo.combinedTextureSamplers = true;                  // This appears to be the requirement of OpenGL backend.

                // In this tutorial, we will load shaders from resources embedded into this .NET DLL.
                var vs = shaderFactory.compileFromFile(assets, "cube.vsh", sourceInfo, "Cube VS");
                stateFactory.graphicsVertexShader(vs);

                // Create dynamic uniform buffer that will store our transformation matrix. Dynamic buffers can be frequently updated by the CPU.
                BufferDesc CBDesc = new BufferDesc(false);
                CBDesc.uiSizeInBytes  = Marshal.SizeOf <Matrix4x4>();
                CBDesc.Usage          = Usage.Dynamic;
                CBDesc.BindFlags      = BindFlags.UniformBuffer;
                CBDesc.CPUAccessFlags = CpuAccessFlags.Write;
                vsConstants           = device.CreateBuffer(CBDesc, "VS constants CB");

                // Create a pixel shader
                sourceInfo.shaderType = ShaderType.Pixel;

                var ps = shaderFactory.compileFromFile(assets, "cube.psh", sourceInfo, "Cube PS");
                stateFactory.graphicsPixelShader(ps);

                // Define vertex shader input layout

                // Attribute 0 - vertex position
                LayoutElement elt = new LayoutElement(false)
                {
                    InputIndex    = 0,
                    BufferSlot    = 0,
                    NumComponents = 3,
                    ValueType     = GpuValueType.Float32,
                    IsNormalized  = false
                };
                stateFactory.graphicsLayoutElement(elt);
                // Attribute 1 - texture coordinates
                elt.InputIndex    = 1;
                elt.NumComponents = 2;
                stateFactory.graphicsLayoutElement(elt);

                // Define variable type that will be used by default
                PSODesc.ResourceLayout.DefaultVariableType = ShaderResourceVariableType.Static;
                // Shader variables should typically be mutable, which means they are expected to change on a per-instance basis
                stateFactory.layoutVariable(ShaderType.Pixel, ShaderResourceVariableType.Mutable, "g_Texture");

                // Define static sampler for g_Texture. Static samplers should be used whenever possible.
                // The default constructor is good enough, it sets FilterType.Linear and TextureAddressMode.Clamp for all 3 coordinates.
                SamplerDesc samplerDesc = new SamplerDesc(false);
                stateFactory.layoutStaticSampler(ShaderType.Pixel, ref samplerDesc, "g_Texture");

                stateFactory.apply(ref PSODesc);
                pipelineState = device.CreatePipelineState(ref PSODesc);
            }

            // Since we did not explicitly specify the type for 'Constants' variable, default
            // type (SHADER_RESOURCE_VARIABLE_TYPE_STATIC) will be used. Static variables never
            // change and are bound directly through the pipeline state object.
            pipelineState.GetStaticVariableByName(ShaderType.Vertex, "Constants").Set(vsConstants);

            // Since we are using mutable variable, we must create a shader resource binding object
            // http://diligentgraphics.com/2016/03/23/resource-binding-model-in-diligent-engine-2-0/
            resourceBinding = pipelineState.CreateShaderResourceBinding(true);
        }
Exemple #36
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="desc"></param>
        public void Initialize(BufferDesc desc)
        {
            var device = GraphicsCore.D3D11Device;

            // 情報取得
            width_  = desc.width;
            height_ = desc.height;
            format_ = desc.format;
            mips_   = desc.mips;
            if (mips_ == 0)
            {
                mips_ = 1;
            }

            BindFlags bindFlags = BindFlags.ShaderResource;

            if (desc.IsRenderTarget)
            {
                bindFlags |= BindFlags.RenderTarget;
            }
            if (desc.IsDepthStencil)
            {
                bindFlags |= BindFlags.DepthStencil;
            }
            if (desc.IsUnorderedAccess)
            {
                bindFlags |= BindFlags.UnorderedAccess;
            }

            CpuAccessFlags acc_flag   = CpuAccessFlags.None;
            ResourceUsage  res_usage  = ResourceUsage.Default;
            bool           isCube     = (desc.optionFlags & ResourceOptionFlags.TextureCube) != 0;
            int            array_size = (!isCube) ? 1 : 6;

            // 初期化データ
            DataRectangle[] dataRect = null;
            if (desc.initData != null)
            {
                dataRect = new DataRectangle[desc.initData.Length * desc.initData[0].Length];
                int index = 0;
                for (int i = 0; i < desc.initData[0].Length; i++)
                {
                    for (int m = 0; m < desc.initData.Length; m++)
                    {
                        dataRect[index++] = new DataRectangle((width_ >> m) * 4, new DataStream(desc.initData[m][i], true, true));
                    }
                }
            }

            // テクスチャオブジェクト
            Texture2DDescription textureDescription = new Texture2DDescription {
                ArraySize      = array_size,
                BindFlags      = bindFlags,
                CpuAccessFlags = acc_flag,
                Format         = desc.format,
                Height         = desc.height,
                Width          = desc.width,
                MipLevels      = mips_,
                //OptionFlags = (mips_ > 1 && needsGpuWrite) ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None,
                OptionFlags       = desc.optionFlags,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = res_usage
            };
            var texture2d = new Texture2D(device, textureDescription, dataRect);

            buffer_ = texture2d;

            // 初期データ解放
            if (dataRect != null)
            {
                foreach (var d in dataRect)
                {
                    d.Data.Close();
                }
            }

            Format srvFormat = desc.format;

            // Special case for depth
            if (desc.IsDepthStencil)
            {
                srvFormat = (desc.format == Format.R32_Typeless) ? Format.R32_Float : Format.R24_UNorm_X8_Typeless;
            }

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription {
                ArraySize       = 0,
                Format          = srvFormat,
                Dimension       = (isCube) ? ShaderResourceViewDimension.TextureCube : ShaderResourceViewDimension.Texture2D,
                Flags           = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels       = mips_
            };

            shaderResourceView_ = new ShaderResourceView(device, texture2d, srvViewDesc);

            // レンダーターゲットビュー
            if (desc.IsRenderTarget)
            {
                if (!isCube)
                {
                    // 通常
                    RenderTargetViewDescription rtViewDesc = new RenderTargetViewDescription {
                        Dimension = RenderTargetViewDimension.Texture2D,
                        Format    = desc.format,
                        MipSlice  = 0,
                    };
                    renderTargetView_ = new RenderTargetView(device, texture2d, rtViewDesc);
                }
                else
                {
                    // キューブマップ
                    RenderTargetViewDescription rtViewDesc = new RenderTargetViewDescription {
                        Dimension = RenderTargetViewDimension.Texture2DArray,
                        Format    = desc.format,
                        MipSlice  = 0,
                        ArraySize = 1,
                    };
                    arrayRenderTargetView_ = new RenderTargetView[array_size * mips_];
                    for (int m = 0; m < mips_; m++)
                    {
                        for (int i = 0; i < array_size; i++)
                        {
                            rtViewDesc.MipSlice               = m;
                            rtViewDesc.FirstArraySlice        = i;
                            arrayRenderTargetView_[m * 6 + i] = new RenderTargetView(device, texture2d, rtViewDesc);
                        }
                    }
                }
            }

            // デプスステンシルビュー
            if (desc.IsDepthStencil)
            {
                DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription {
                    ArraySize       = 0,
                    Format          = (desc.format == Format.R32_Typeless) ? Format.D32_Float : Format.D24_UNorm_S8_UInt,
                    Dimension       = DepthStencilViewDimension.Texture2D,
                    MipSlice        = 0,
                    Flags           = 0,
                    FirstArraySlice = 0
                };

                depthStencilView_ = new DepthStencilView(device, texture2d, dsViewDesc);
            }

            // UAV
            if (desc.IsUnorderedAccess)
            {
                UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription {
                    ArraySize       = 0,
                    DepthSliceCount = 1,
                    Dimension       = UnorderedAccessViewDimension.Texture2D,
                    ElementCount    = 1,
                    FirstArraySlice = 0,
                    FirstDepthSlice = 0,
                    FirstElement    = 0,
                    Flags           = UnorderedAccessViewBufferFlags.None,
                    Format          = desc.format,
                    MipSlice        = 0
                };
                unorderedAccessView_ = new UnorderedAccessView(device, texture2d, uavDesc);
            }
        }
Exemple #37
0
        private void CreateGeometry()
        {
            // Create box
            Geometry box = new Geometry(OptixContext);

            box.PrimitiveCount      = 1;
            box.BoundingBoxProgram  = new OptixProgram(OptixContext, boxPath, "box_bounds");;
            box.IntersectionProgram = new OptixProgram(OptixContext, boxPath, "box_intersect");;
            box["boxmin"].Set(-2.0f, 0.0f, -2.0f);
            box["boxmax"].Set(2.0f, 7.0f, 2.0f);

            Geometry chull = null;

            if (mTutorial >= 9)
            {
                chull = new Geometry(OptixContext);
                chull.PrimitiveCount      = 1u;
                chull.BoundingBoxProgram  = new OptixProgram(OptixContext, shaderPath, "chull_bounds");
                chull.IntersectionProgram = new OptixProgram(OptixContext, shaderPath, "chull_intersect");

                uint    nsides = 6;
                float   radius = 1;
                Vector3 xlate  = new Vector3(-1.4f, 0, -3.7f);

                BufferDesc desc = new BufferDesc()
                {
                    Width = nsides + 2u, Type = BufferType.Input, Format = Format.Float4
                };
                Buffer chullBuffer = new Buffer(OptixContext, desc);

                float        angle  = 0.0f;
                BufferStream stream = chullBuffer.Map();
                for (uint i = 0; i < nsides; i++)
                {
                    angle = (float)i / (float)nsides * (float)Math.PI * 2.0f;
                    float x = (float)Math.Cos(angle);
                    float y = (float)Math.Sin(angle);

                    stream.Write <Vector4>(Utils.CreatePlane(new Vector3(x, 0, y), new Vector3(x * radius, 0, y * radius) + xlate));
                }

                float min = 0.02f;
                float max = 3.5f;
                angle = 5.0f / (float)nsides * (float)Math.PI * 2.0f;
                stream.Write <Vector4>(Utils.CreatePlane(new Vector3(0, -1, 0), new Vector3(0, min, 0) + xlate));
                stream.Write <Vector4>(Utils.CreatePlane(new Vector3((float)Math.Cos(angle), 0.7f, (float)Math.Sin(angle)),
                                                         new Vector3(0, max, 0) + xlate));

                chullBuffer.Unmap();

                chull["planes"].Set(chullBuffer);
                chull["chull_bbmin"].Set(-radius + xlate.X, min + xlate.Y, -radius + xlate.Z);
                chull["chull_bbmax"].Set(radius + xlate.X, max + xlate.Y, radius + xlate.Z);
            }

            // Floor geometry
            Geometry parallelogram = new Geometry(OptixContext);

            parallelogram.PrimitiveCount      = 1;
            parallelogram.BoundingBoxProgram  = new OptixProgram(OptixContext, parrallelPath, "bounds");;
            parallelogram.IntersectionProgram = new OptixProgram(OptixContext, parrallelPath, "intersect");;

            Vector3 anchor = new Vector3(-64.0f, 0.01f, -64.0f);
            Vector3 v1     = new Vector3(128.0f, 0.0f, 0.0f);
            Vector3 v2     = new Vector3(0.0f, 0.0f, 128.0f);
            Vector3 normal = Vector3.Normalize(Vector3.Cross(v2, v1));

            v1 *= 1.0f / (v1.LengthSquared());
            v2 *= 1.0f / (v2.LengthSquared());

            float   d     = Vector3.Dot(normal, anchor);
            Vector4 plane = new Vector4(normal, d);

            parallelogram["plane"].Set(ref plane);
            parallelogram["v1"].Set(ref v1);
            parallelogram["v2"].Set(ref v2);
            parallelogram["anchor"].Set(ref anchor);

            string boxMtrlName   = mTutorial >= 8 ? "box_closest_hit_radiance" : "closest_hit_radiance";
            string floorMtrlName = mTutorial >= 4 ? "floor_closest_hit_radiance" : "closest_hit_radiance";

            Material boxMtrl = new Material(OptixContext);

            boxMtrl.SetSurfaceProgram(0, new SurfaceProgram(OptixContext, RayHitType.Closest, shaderPath, boxMtrlName));
            if (mTutorial >= 3)
            {
                boxMtrl.SetSurfaceProgram(1, new SurfaceProgram(OptixContext, RayHitType.Any, shaderPath, "any_hit_shadow"));
            }

            boxMtrl["Ka"].Set(0.3f, 0.3f, 0.3f);
            boxMtrl["Kd"].Set(0.6f, 0.7f, 0.8f);
            boxMtrl["Ks"].Set(0.8f, 0.9f, 0.8f);
            boxMtrl["phong_exp"].Set(88.0f);
            boxMtrl["reflectivity_n"].Set(0.2f, 0.2f, 0.2f);

            Material floorMtrl = new Material(OptixContext);

            floorMtrl.SetSurfaceProgram(0, new SurfaceProgram(OptixContext, RayHitType.Closest, shaderPath, floorMtrlName));
            if (mTutorial >= 3)
            {
                floorMtrl.SetSurfaceProgram(1, new SurfaceProgram(OptixContext, RayHitType.Any, shaderPath, "any_hit_shadow"));
            }

            floorMtrl["Ka"].Set(0.3f, 0.3f, 0.1f);
            floorMtrl["Kd"].Set(194 / 255.0f * .6f, 186 / 255.0f * .6f, 151 / 255.0f * .6f);
            floorMtrl["Ks"].Set(0.4f, 0.4f, 0.4f);
            floorMtrl["reflectivity"].Set(0.1f, 0.1f, 0.1f);
            floorMtrl["reflectivity_n"].Set(0.05f, 0.05f, 0.05f);
            floorMtrl["phong_exp"].Set(88.0f);
            floorMtrl["tile_v0"].Set(0.25f, 0, .15f);
            floorMtrl["tile_v1"].Set(-.15f, 0, 0.25f);
            floorMtrl["crack_color"].Set(0.1f, 0.1f, 0.1f);
            floorMtrl["crack_width"].Set(0.02f);

            Material glassMtrl = null;

            if (chull != null)
            {
                glassMtrl = new Material(OptixContext);
                glassMtrl.SetSurfaceProgram(0, new SurfaceProgram(OptixContext, RayHitType.Closest, shaderPath, "glass_closest_hit_radiance"));
                glassMtrl.SetSurfaceProgram(1, new SurfaceProgram(OptixContext, RayHitType.Any, shaderPath, mTutorial > 9 ? "glass_any_hit_shadow" : "any_hit_shadow"));

                Vector3 extinction = new Vector3(.80f, .89f, .75f);
                glassMtrl["importance_cutoff"].Set(1e-2f);
                glassMtrl["cutoff_color"].Set(0.34f, 0.55f, 0.85f);
                glassMtrl["fresnel_exponent"].Set(3.0f);
                glassMtrl["fresnel_minimum"].Set(0.1f);
                glassMtrl["fresnel_maximum"].Set(1.0f);
                glassMtrl["refraction_index"].Set(1.4f);
                glassMtrl["refraction_color"].Set(1.0f, 1.0f, 1.0f);
                glassMtrl["reflection_color"].Set(1.0f, 1.0f, 1.0f);
                glassMtrl["refraction_maxdepth"].Set(100);
                glassMtrl["reflection_maxdepth"].Set(100);
                glassMtrl["extinction_constant"].Set((float)Math.Log(extinction.X), (float)Math.Log(extinction.Y), (float)Math.Log(extinction.Z));
                glassMtrl["shadow_attenuation"].Set(0.4f, 0.7f, 0.4f);
            }

            GeometryInstance boxInst = new GeometryInstance(OptixContext);

            boxInst.Geometry = box;
            boxInst.AddMaterial(boxMtrl);

            GeometryInstance parallelInst = new GeometryInstance(OptixContext);

            parallelInst.Geometry = parallelogram;
            parallelInst.AddMaterial(floorMtrl);

            GeometryGroup group = new GeometryGroup(OptixContext);

            group.AddChild(boxInst);
            group.AddChild(parallelInst);
            if (chull != null)
            {
                GeometryInstance chullInst = new GeometryInstance(OptixContext);
                chullInst.Geometry = chull;
                chullInst.AddMaterial(glassMtrl);
                group.AddChild(chullInst);
            }

            group.Acceleration = new Acceleration(OptixContext, AccelBuilder.Bvh, AccelTraverser.Bvh);

            OptixContext["top_object"].Set(group);
            OptixContext["top_shadower"].Set(group);
        }
Exemple #38
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="desc"></param>
 public StructuredBuffer(BufferDesc desc)
 {
     Initialize(desc);
 }
Exemple #39
0
        protected void CreateOutputBuffer(Format format) {
            if (UsePBO) {
                //Allocate first the memory for the gl buffer, then attach it to OptiX.
                uint pbo = CreatePBO(format);

                OGLBufferDesc glDesc = new OGLBufferDesc() {
                    Width = (uint)Width,
                    Height = (uint)Height,
                    Format = format,
                    Type = BufferType.Output,
                    Resource = pbo
                };
                OutputBuffer = new OGLBuffer(Context,  glDesc);
            }
            else {
                BufferDesc desc = new BufferDesc() {
                    Width = (uint)Width,
                    Height = (uint)Height,
                    Format = format,
                    Type = BufferType.Output
                };
                OutputBuffer = EngineContext.Instance.ResourceManager.CreateBuffer(Context, desc);
            }
        }
Exemple #40
0
 public VertexBuffer(BufferDesc desc)
 {
     buffer_  = new D3D11Buffer(GraphicsCore.D3D11Device, desc.data, desc.data_size, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
     Stride   = desc.stride;
     Topology = RenderState.PrimitiveTopology.TriangleList;
 }
Exemple #41
0
        protected void UpdateDescriptionBuffer()
        {
            var optixContext = ComponentPipeline.Instance.Session.OptixContext;
            var descriptions = builder.MaterialDescriptions.ToArray();

            if (mdBuffer != null)
            {
                mdBuffer.Destroy();
                mdBuffer = null;
            }
            var mdBuffDesc = new BufferDesc
            {
                Width = (ulong)descriptions.Length,
                Format = Format.User,
                Type = BufferType.Input,
                ElemSize = (uint)Marshal.SizeOf(typeof(MaterialDescription))
            };
            mdBuffer = new Buffer(optixContext, mdBuffDesc);
            mdBuffer.SetData(descriptions);
            optixContext["materialDescriptions"].Set(mdBuffer);
        }