/// <inheritdoc/>
        protected internal override void OnDestroyed()
        {
            GraphicsDevice.Collect(NativeSampler);
            NativeSampler = Sampler.Null;

            base.OnDestroyed();
        }
    public void Init(string s)
    {
        animation = GetComponent<VillagerAnimation>();
		animation.Init (s);

        skinMaterial = GetComponentInChildren<MeshRenderer>().material;
        origColor = skinMaterial.color;

        // music stuff
        musicToggle = GetComponent<ToggleSuspend>();
        musicPattern = GetComponent<Pattern>();
        SetMusicPattern();
        musicSample = GetComponent<Sampler>();
        SetMusicSample();

		keyboardPosition = transform.localPosition;

        textMesh = GetComponentInChildren<TextMesh>();

        letter = s;
        textMesh.text = s;

		currentState = State.Idle;
		timeSinceLastDanced = Time.time;
    }
Beispiel #3
0
        public FloatMapImage RenderImage(Size imageSize)
        {
            int height = imageSize.Height;
            int width = imageSize.Width;
            FloatMapImage outputImage = new FloatMapImage((uint)width, (uint)height, PixelFormat.Greyscale);
            Sensor.RasterSize = imageSize;

            Sampler sampler = new Sampler();
            int SqrtSampleCount = (int)Math.Sqrt(SampleCount);
            foreach (Vector2d sample in sampler.GenerateJitteredSamples(SqrtSampleCount))
            {
                // generate a sample at the lens surface
                Vector3d lensPos = Lens.GetBackSurfaceSample(sample);
                lensPos.Z = 0;
                // make an incoming ray from the light source to the lens sample and
                // transfer the incoming ray through the lens creating the outgoing ray
                Ray outgoingRay = Lens.Transfer(LightSourcePosition, lensPos);
                if (outgoingRay == null)
                {
                    continue;
                }
                // intersect the senzor with the outgoing ray
                Intersection intersection = Sensor.Intersect(outgoingRay);
                if (intersection == null)
                {
                    continue;
                }
                Vector3d intersectionPoint = intersection.Position;
                Vector2d intersectionPixelPoint = Sensor.CameraToImage(intersectionPoint);
                // put a splat on the senzor at the intersection
                Splat(outputImage, LightIntensity, intersectionPixelPoint);
            }

            return outputImage;
        }
        internal static unsafe SharpVulkan.DescriptorSetLayout CreateNativeDescriptorSetLayout(GraphicsDevice device, IList<DescriptorSetLayoutBuilder.Entry> entries, out uint[] typeCounts)
        {
            var bindings = new DescriptorSetLayoutBinding[entries.Count];
            var immutableSamplers = new Sampler[entries.Count];

            int usedBindingCount = 0;

            typeCounts = new uint[DescriptorTypeCount];

            fixed (Sampler* immutableSamplersPointer = &immutableSamplers[0])
            {
                for (int i = 0; i < entries.Count; i++)
                {
                    var entry = entries[i];

                    // TODO VULKAN: Special case for unused bindings in PipelineState. Handle more nicely.
                    if (entry.ArraySize == 0)
                        continue;

                    bindings[usedBindingCount] = new DescriptorSetLayoutBinding
                    {
                        DescriptorType = VulkanConvertExtensions.ConvertDescriptorType(entry.Class, entry.Type),
                        StageFlags = ShaderStageFlags.All, // TODO VULKAN: Filter?
                        Binding = (uint)i,
                        DescriptorCount = (uint)entry.ArraySize
                    };

                    if (entry.ImmutableSampler != null)
                    {
                        // TODO VULKAN: Handle immutable samplers for DescriptorCount > 1
                        if (entry.ArraySize > 1)
                        {
                            throw new NotImplementedException();
                        }

                        // Remember this, so we can choose the right DescriptorType in DescriptorSet.SetShaderResourceView
                        immutableSamplers[i] = entry.ImmutableSampler.NativeSampler;
                        //bindings[i].DescriptorType = DescriptorType.CombinedImageSampler;
                        bindings[usedBindingCount].ImmutableSamplers = new IntPtr(immutableSamplersPointer + i);
                    }

                    typeCounts[(int)bindings[usedBindingCount].DescriptorType] += bindings[usedBindingCount].DescriptorCount;

                    usedBindingCount++;
                }

                var createInfo = new DescriptorSetLayoutCreateInfo
                {
                    StructureType = StructureType.DescriptorSetLayoutCreateInfo,
                    BindingCount = (uint)usedBindingCount,
                    Bindings = usedBindingCount > 0 ? new IntPtr(Interop.Fixed(bindings)) : IntPtr.Zero
                };
                return device.NativeDevice.CreateDescriptorSetLayout(ref createInfo);
            }
        }
        public void GenerateJitteredSamples()
        {
            Stopwatch sw = Stopwatch.StartNew();

            Sampler sampler = new Sampler();
            //foreach (var sample in sampler.GenerateJitteredSamples(512)) ;
            foreach (var sample in sampler.GenerateUniformPoints(256 * 1024)) ;

            sw.Stop();
            Console.WriteLine("Total time: {0}", sw.ElapsedMilliseconds);
            Console.WriteLine("Thoughput: {0} smpl/sec", 512 * 512 * (1000 / (float)sw.ElapsedMilliseconds));
        }
Beispiel #6
0
        public void TraceRays()
        {
            ComplexLens lens = ComplexLens.CreateBiconvexLens(4, 2, 0);

            Sampler sampler = new Sampler();
            int sampleCount = 64;
            int sqrtSampleCount = (int)Math.Sqrt(sampleCount);
            Vector3d objectPos = new Vector3d(10, 0, 100);
            foreach (Vector2d sample in sampler.GenerateJitteredSamples(sqrtSampleCount))
            {
                Vector3d lensPos = lens.GetBackSurfaceSample(sample);
                Ray result = lens.Transfer(objectPos, lensPos);
            }
        }
Beispiel #7
0
        public void TraceParallelRays()
        {
            BiconvexLens lens = new BiconvexLens();
            lens.ApertureRadius = 2;
            lens.CurvatureRadius = 4;

            Sampler sampler = new Sampler();
            int sampleCount = 64;
            int sqrtSampleCount = (int)Math.Sqrt(sampleCount);
            Vector3d objectPos = new Vector3d(10, 0, 100);
            foreach (Vector2d sample in sampler.GenerateJitteredSamples(sqrtSampleCount))
            {
                Vector3d lensPos = lens.GetBackSurfaceSample(sample);
                //Vector3d objectPos = lensPos + 10 * Vector3d.UnitZ + 2 * Vector3d.UnitX;
                Ray result = lens.Transfer(objectPos, lensPos);
            }
        }
Beispiel #8
0
        public void TraceSingleRay()
        {
            ComplexLens lens = ComplexLens.CreateBiconvexLens(4, 2, 0);

            Sampler sampler = new Sampler();
            int sampleCount = 64;
            int sqrtSampleCount = (int)Math.Sqrt(sampleCount);
            Vector3d objectPos = new Vector3d(10, 0, 100);
            Vector3d direction = new Vector3d(0, 0, 0);
            Ray ray = new Ray(objectPos, direction);
            Intersection isec = lens.Intersect(ray);
            if (isec == null)
            {
                return;
            }
            Ray result = lens.Transfer(objectPos, isec.Position);
        }
        private unsafe void CreateNativeSampler()
        {
            var createInfo = new SamplerCreateInfo
            {
                StructureType = StructureType.SamplerCreateInfo,
                AddressModeU = ConvertAddressMode(Description.AddressU),
                AddressModeV = ConvertAddressMode(Description.AddressV),
                AddressModeW = ConvertAddressMode(Description.AddressW),
                MipLodBias = Description.MipMapLevelOfDetailBias,
                MaxAnisotropy = Description.MaxAnisotropy,
                CompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(Description.CompareFunction),
                MinLod = Description.MinMipLevel,
                MaxLod = Description.MaxMipLevel,
                BorderColor = BorderColor.FloatOpaqueBlack // TODO VULKAN: How to handle BorderColor
            };

            ConvertMinFilter(Description.Filter, out createInfo.MinFilter, out createInfo.MagFilter, out createInfo.MipmapMode, out createInfo.CompareEnable, out createInfo.AnisotropyEnable);

            NativeSampler = GraphicsDevice.NativeDevice.CreateSampler(ref createInfo);
        }
Beispiel #10
0
        public void IntersectSphere()
        {
            Sphere sphere = new Sphere()
            {
                Radius = 2
            };
            double biggerSphereFactor = 3;

            Sampler sampler = new Sampler();
            int sampleCount = 64;
            int sqrtSampleCount = (int)Math.Sqrt(sampleCount);
            foreach (Vector2d sample in sampler.GenerateJitteredSamples(sqrtSampleCount))
            {
                // shoot rays at the sphere center from a bigger concontric sphere
                Vector3d unitSphereSample = Sampler.UniformSampleSphereWithEqualArea(sample, -1, 1);
                Vector3d sourcePos = biggerSphereFactor * sphere.Radius * unitSphereSample;
                Ray ray = new Ray(sourcePos, sphere.Center - sourcePos);
                Intersection intersection = sphere.Intersect(ray);
                Assert.NotNull(intersection);
                Vector3d intPos = intersection.Position;
                Console.WriteLine("Black, {0},", ray.ToLine());
                Console.WriteLine(String.Format("Red, {0},", intPos.ToPoint()));
            }
        }
Beispiel #11
0
        List <StateGroupAsset> loadStateGroups()
        {
            var stateGroups = new List <StateGroupAsset>();

            if (!Directory.Exists(metadataPath + "StateGroups"))
            {
                Directory.CreateDirectory(metadataPath + "StateGroups");
            }

            foreach (var filename in Directory.EnumerateFiles(metadataPath + "StateGroups"))
            {
                var metadata = File.ReadAllLines(filename);

                var stateGroup = new StateGroupAsset();

                stateGroup.Name              = System.IO.Path.GetFileNameWithoutExtension(filename);
                stateGroup.Description       = metadata[0].Split('=')[1].Trim();
                stateGroup.LastUpdated       = parseLastUpdatedDate(metadata[1].Split('=')[1].Trim(), "stateGroup", stateGroup.Name);
                stateGroup.VertexShaderId    = metadata[2].Split('=')[1].Trim();
                stateGroup.GeometryShaderId  = metadata[3].Split('=')[1].Trim();
                stateGroup.PixelShaderId     = metadata[4].Split('=')[1].Trim();
                stateGroup.ShaderCombination = (ShaderCombination)Enum.Parse(typeof(ShaderCombination), metadata[5].Split('=')[1].Trim());
                stateGroup.ImportedFilename  = metadata[6].Split('=')[1].Trim();
                stateGroup.ImporterVersion   = int.Parse(metadata[7].Split('=')[1].Trim());

                var samplerLine    = metadata[8].Split('=')[1].Trim();
                var samplerConfigs = samplerLine.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var config in samplerConfigs)
                {
                    var data    = config.Split(',');
                    var sampler = new Sampler()
                    {
                        Name     = data[0].Trim(),
                        Filter   = (Filter)Enum.Parse(typeof(Filter), data[1].Trim()),
                        AddressU = (TextureAddressMode)Enum.Parse(typeof(TextureAddressMode), data[2].Trim()),
                        AddressV = (TextureAddressMode)Enum.Parse(typeof(TextureAddressMode), data[3].Trim()),
                        AddressW = (TextureAddressMode)Enum.Parse(typeof(TextureAddressMode), data[4].Trim())
                    };

                    stateGroup.Samplers.Add(sampler);
                }

                var textureLine    = metadata[9].Split('=')[1].Trim();
                var textureConfigs = textureLine.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var config in textureConfigs)
                {
                    var data    = config.Split(',');
                    var texture = new TextureBinding()
                    {
                        Slot    = Int32.Parse(data[0].Trim()),
                        Binding = data[1].Trim()
                    };

                    stateGroup.TextureBindings.Add(texture);
                }

                var blendStateLine = metadata[10].Split('=')[1].Trim();
                var blendConfigs   = blendStateLine.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var config in blendConfigs)
                {
                    var data = config.Split(',');

                    var renderTarget = new RenderTarget()
                    {
                        Index                 = int.Parse(data[0].Trim()),
                        BlendEnabled          = bool.Parse(data[1].Trim()),
                        BlendOperation        = (BlendOperation)Enum.Parse(typeof(BlendOperation), data[2].Trim()),
                        BlendOperationAlpha   = (BlendOperation)Enum.Parse(typeof(BlendOperation), data[3].Trim()),
                        SourceBlend           = (BlendOption)Enum.Parse(typeof(BlendOption), data[4].Trim()),
                        DestinationBlend      = (BlendOption)Enum.Parse(typeof(BlendOption), data[5].Trim()),
                        SourceBlendAlpha      = (BlendOption)Enum.Parse(typeof(BlendOption), data[6].Trim()),
                        DestinationBlendAlpha = (BlendOption)Enum.Parse(typeof(BlendOption), data[7].Trim()),
                        RenderTargetWriteMask = (WriteMask)Enum.Parse(typeof(WriteMask), data[8].Trim())
                    };

                    stateGroup.BlendState.RenderTargets.Add(renderTarget);
                }

                stateGroups.Add(stateGroup);
            }

            return(stateGroups);
        }
 public ZipkinSpanWriter(Sampler sampler)
 {
     this.sampler = sampler;
 }
Beispiel #13
0
        public ImportResult Import(GLTFAccessor.ImportResult[] accessors, GLTFNode.ImportResult[] nodes, ImportSettings importSettings)
        {
            bool multiRoots = nodes.Where(x => x.IsRoot).Count() > 1;

            ImportResult result = new ImportResult();

            result.clip           = new AnimationClip();
            result.clip.name      = name;
            result.clip.frameRate = importSettings.animationSettings.frameRate;

            result.clip.legacy = importSettings.animationSettings.useLegacyClips;

            if (result.clip.legacy && importSettings.animationSettings.looping)
            {
                result.clip.wrapMode = WrapMode.Loop;
            }

            for (int i = 0; i < channels.Length; i++)
            {
                Channel channel = channels[i];
                if (samplers.Length <= channel.sampler)
                {
                    Debug.LogWarning($"GLTFUtility: Animation channel points to sampler at index {channel.sampler} which doesn't exist. Skipping animation clip.");
                    continue;
                }
                Sampler sampler = samplers[channel.sampler];

                // Get interpolation mode
                InterpolationMode interpolationMode = importSettings.animationSettings.interpolationMode;
                if (interpolationMode == InterpolationMode.ImportFromFile)
                {
                    interpolationMode = sampler.interpolation;
                }
                if (interpolationMode == InterpolationMode.CUBICSPLINE)
                {
                    Debug.LogWarning("Animation interpolation mode CUBICSPLINE not fully supported, result might look different.");
                }

                string relativePath = "";

                GLTFNode.ImportResult node = nodes[channel.target.node.Value];
                while (node != null && !node.IsRoot)
                {
                    if (string.IsNullOrEmpty(relativePath))
                    {
                        relativePath = node.transform.name;
                    }
                    else
                    {
                        relativePath = node.transform.name + "/" + relativePath;
                    }

                    if (node.parent.HasValue)
                    {
                        node = nodes[node.parent.Value];
                    }
                    else
                    {
                        node = null;
                    }
                }

                // If file has multiple root nodes, a new parent will be created for them as a final step of the import process. This parent f***s up the curve relative paths.
                // Add node.transform.name to path if there are multiple roots. This is not the most elegant fix but it works.
                // See GLTFNodeExtensions.GetRoot
                if (multiRoots)
                {
                    relativePath = node.transform.name + "/" + relativePath;
                }

                System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
                float[] keyframeInput = accessors[sampler.input].ReadFloat().ToArray();
                switch (channel.target.path)
                {
                case "translation":
                    Vector3[]      pos  = accessors[sampler.output].ReadVec3().ToArray();
                    AnimationCurve posX = new AnimationCurve();
                    AnimationCurve posY = new AnimationCurve();
                    AnimationCurve posZ = new AnimationCurve();
                    for (int k = 0; k < keyframeInput.Length; k++)
                    {
                        posX.AddKey(CreateKeyframe(k, keyframeInput, pos, x => - x.x, interpolationMode));
                        posY.AddKey(CreateKeyframe(k, keyframeInput, pos, x => x.y, interpolationMode));
                        posZ.AddKey(CreateKeyframe(k, keyframeInput, pos, x => x.z, interpolationMode));
                    }
                    result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ);
                    break;

                case "rotation":
                    Vector4[]      rot  = accessors[sampler.output].ReadVec4().ToArray();
                    AnimationCurve rotX = new AnimationCurve();
                    AnimationCurve rotY = new AnimationCurve();
                    AnimationCurve rotZ = new AnimationCurve();
                    AnimationCurve rotW = new AnimationCurve();
                    for (int k = 0; k < keyframeInput.Length; k++)
                    {
                        // The Animation window in Unity shows keyframes incorrectly converted to euler. This is only to deceive you. The quaternions underneath work correctly
                        rotX.AddKey(CreateKeyframe(k, keyframeInput, rot, x => x.x, interpolationMode));
                        rotY.AddKey(CreateKeyframe(k, keyframeInput, rot, x => - x.y, interpolationMode));
                        rotZ.AddKey(CreateKeyframe(k, keyframeInput, rot, x => - x.z, interpolationMode));
                        rotW.AddKey(CreateKeyframe(k, keyframeInput, rot, x => x.w, interpolationMode));
                    }
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW);
                    break;

                case "scale":
                    Vector3[]      scale  = accessors[sampler.output].ReadVec3().ToArray();
                    AnimationCurve scaleX = new AnimationCurve();
                    AnimationCurve scaleY = new AnimationCurve();
                    AnimationCurve scaleZ = new AnimationCurve();
                    for (int k = 0; k < keyframeInput.Length; k++)
                    {
                        scaleX.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.x, interpolationMode));
                        scaleY.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.y, interpolationMode));
                        scaleZ.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.z, interpolationMode));
                    }
                    result.clip.SetCurve(relativePath, typeof(Transform), "localScale.x", scaleX);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localScale.y", scaleY);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localScale.z", scaleZ);
                    break;

                case "weights":
                    GLTFNode.ImportResult skinnedMeshNode     = nodes[channel.target.node.Value];
                    SkinnedMeshRenderer   skinnedMeshRenderer = skinnedMeshNode.transform.GetComponent <SkinnedMeshRenderer>();

                    int numberOfBlendShapes           = skinnedMeshRenderer.sharedMesh.blendShapeCount;
                    AnimationCurve[] blendShapeCurves = new AnimationCurve[numberOfBlendShapes];
                    for (int j = 0; j < numberOfBlendShapes; ++j)
                    {
                        blendShapeCurves[j] = new AnimationCurve();
                    }

                    float[] weights      = accessors[sampler.output].ReadFloat().ToArray();
                    float[] weightValues = new float[keyframeInput.Length];

                    float[] previouslyKeyedValues = new float[numberOfBlendShapes];

                    // Reference for my future self:
                    // keyframeInput.Length = number of keyframes
                    // keyframeInput[ k ] = timestamp of keyframe
                    // weights.Length = number of keyframes * number of blendshapes
                    // weights[ j ] = actual animated weight of a specific blend shape
                    // (index into weights[] array accounts for keyframe index and blend shape index)

                    for (int k = 0; k < keyframeInput.Length; ++k)
                    {
                        for (int j = 0; j < numberOfBlendShapes; ++j)
                        {
                            int weightIndex = (k * numberOfBlendShapes) + j;
                            weightValues[k] = weights[weightIndex];

                            bool addKey = true;
                            if (importSettings.animationSettings.compressBlendShapeKeyFrames)
                            {
                                if (k == 0 || !Mathf.Approximately(weightValues[k], previouslyKeyedValues[j]))
                                {
                                    if (k > 0)
                                    {
                                        weightValues[k - 1] = previouslyKeyedValues[j];
                                        blendShapeCurves[j].AddKey(CreateKeyframe(k - 1, keyframeInput, weightValues, x => x, interpolationMode));
                                    }
                                    addKey = true;
                                    previouslyKeyedValues[j] = weightValues[k];
                                }
                                else
                                {
                                    addKey = false;
                                }
                            }

                            if (addKey)
                            {
                                blendShapeCurves[j].AddKey(CreateKeyframe(k, keyframeInput, weightValues, x => x, interpolationMode));
                            }
                        }
                    }

                    for (int j = 0; j < numberOfBlendShapes; ++j)
                    {
                        string propertyName = "blendShape." + skinnedMeshRenderer.sharedMesh.GetBlendShapeName(j);
                        result.clip.SetCurve(relativePath, typeof(SkinnedMeshRenderer), propertyName, blendShapeCurves[j]);
                    }
                    break;
                }
            }
            return(result);
        }
        /// <summary>
        /// Computes 1) a boolean specifying whether the intersection was on the right side 2) the lightmap UVs 3) the texture sample color 4) the new ray direction.
        /// </summary>
        /// <param name="direction">The direction the photon was traveling when it struck the surface.</param>
        /// <param name="a">Triangle vertex.</param>
        /// <param name="b">Triangle vertex.</param>
        /// <param name="c">Triangle vertex.</param>
        /// <param name="intersection">Intersection data returned by EnhancedMesh.Intersect</param>
        /// <param name="textureSampler">A sampler to sample the BSPs basemap texture.</param>
        /// <returns></returns>
        public static RadiosityIntersection ProcessIntersection(Vector3 direction, Vertex a, Vertex b, Vertex c, Intersection intersection, Sampler textureSampler, bool specular)
        {
            if (intersection == Intersection.None)
            {
                return(RadiosityIntersection.None);
            }

            RadiosityIntersection radIntersect = new RadiosityIntersection(intersection);
            Vector3 normal = ComputeTriangleNormal(a, b, c);

            radIntersect.WrongSide = CheckCollisionSide(direction, normal);
            if (Random.NextDouble() > RadiosityDiffuseConstant)
            {
                radIntersect.Absorbed = true;
            }
            if (specular)
            {
                radIntersect.NewDirection = SpecularReflect(direction, normal);
            }
            else
            {
                radIntersect.NewDirection = DiffuseReflect(normal);
            }
            radIntersect.Scale = 1f; // TODO: Is this even necessary?

            Vector2 lightmapUV = ConvertBaryToTextureCoords(a, b, c, intersection);
            Vector2 textureUV  = ConvertBaryToTextureCoords(a, b, c, intersection);

            radIntersect.U = lightmapUV.X;
            radIntersect.V = lightmapUV.Y;

            if (textureSampler != null)
            {
                radIntersect.TextureSampleColor = textureSampler.Sample(textureUV);
            }
            return(radIntersect);
        }
Beispiel #15
0
 public SamplerKey(Sampler sampler)
 {
     m_FilterMode = sampler.filterMode;
     m_WrapModeU  = sampler.wrapU;
     m_WrapModeV  = sampler.wrapV;
 }
        private void GenerateLensSamplesTextures(int textureId, int totalSampleCount, int tileSize)
        {
            // size of a group of samples for a single pixel
            int bands = 2;
            int textureSize = bands * totalSampleCount * tileSize * tileSize;

            //IEnumerable<Vector2d> samples = GenerateLensSamples(tileSize, (int)Math.Sqrt(MaxTotalSampleCount)).GetEnumerator();

            int sqrtTotalSampleCount = (int)Math.Sqrt(totalSampleCount);
            Vector2[, ,] samples = new Vector2[tileSize, tileSize, totalSampleCount];
            Sampler sampler = new Sampler();

            for (int y = 0; y < tileSize; y++)
            {
                for (int x = 0; x < tileSize; x++)
                {
                    IEnumerable<Vector2> pixelSamples = sampler.CreateLensSamplesFloat(sqrtTotalSampleCount, ShuffleLensSamples);
                    int z = 0;
                    foreach (Vector2 sample in pixelSamples)
                    {
                        samples[x, y, z] = sample;
                        z++;
                    }
                }
            }

            GL.BindTexture(TextureTarget.Texture3D, textureId);

            IntPtr texturePtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Half)) * textureSize);
            unsafe
            {
                int zStride = bands * tileSize * tileSize;
                for (int y = 0; y < tileSize; y++)
                {
                    for (int x = 0; x < tileSize; x++)
                    {
                        Half* row = (Half*)texturePtr + bands * (y * tileSize + x);
                        int index = 0;
                        // Z dimension
                        for (int sample = 0; sample < totalSampleCount; sample++)
                        {
                            Vector2 lensPos = samples[x, y, sample];
                            row[index] = (Half)lensPos.X;
                            row[index + 1] = (Half)lensPos.Y;
                            index += zStride;
                        }
                    }
                }
            }

            // TODO: could be an half float or unsigned byte instead of a float
            // TODO: two sample pair could be stored in one 4-channel value
            GL.TexImage3D(TextureTarget.Texture3D, 0, PixelInternalFormat.Rg16f,
                tileSize, tileSize, totalSampleCount, 0,
                PixelFormat.Rg, PixelType.HalfFloat, texturePtr);

            Marshal.FreeHGlobal(texturePtr);

            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapR, (int)TextureWrapMode.Clamp);
        }
Beispiel #17
0
 internal static unsafe extern void vkDestroySampler(Device device, Sampler sampler, AllocationCallbacks* allocator);
Beispiel #18
0
 public DisposableSampler(Vk api, Device device, Sampler sampler)
 {
     _api    = api;
     _device = device;
     Value   = sampler;
 }
Beispiel #19
0
 public void Dispose()
 {
     Sampler?.Dispose();
     Reporter?.Dispose();
 }
Beispiel #20
0
        private void setReplicasButton_Click(object sender, EventArgs e)
        {
            ReplicaConfiguration config = DemoLib.GetCurrentConfiguration();

            config.PrimaryServers.Clear();
            config.SecondaryServers.Clear();
            config.NonReplicaServers.Clear();
            string server = DemoLib.ServerName("West US");

            if (radioButtonWestUSPrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonWestUSSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("East US");
            if (radioButtonEastUSPrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonEastUSSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("South US");
            if (radioButtonSouthUSPrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonSouthUSSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("North US");
            if (radioButtonNorthUSPrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonNorthUSSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("West Europe");
            if (radioButtonWestEuropePrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonWestEuropeSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("North Europe");
            if (radioButtonNorthEuropePrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonNorthEuropeSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("East Asia");
            if (radioButtonAsiaPrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonAsiaSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            server = DemoLib.ServerName("Brazil");
            if (radioButtonBrazilPrimary.Checked)
            {
                config.PrimaryServers.Add(server);
            }
            else if (radioButtonBrazilSecondary.Checked)
            {
                config.SecondaryServers.Add(server);
            }
            else
            {
                config.NonReplicaServers.Add(server);
            }
            initialConfig   = false;
            reconfigSampler = DemoLib.NewSampler();
            DemoLib.SetCurrentConfiguration(config);
        }
Beispiel #21
0
        //static LinearInterpolation linearInterpolation = new LinearInterpolation();
        //static CubicInterpolation cubicInterpolation = new CubicInterpolation();
        //TODO: legyen allapotmentes a maradek is?

        public static VerifierBenchmark Build(BenchmarkConfig config, string databasePath = null)
        {
            if (databasePath == null)
            {
                databasePath = Environment.GetEnvironmentVariable("SigStatDB");
            }

            svcLoader      = new Svc2004Loader(Path.Combine(databasePath, "SVC2004.zip"), true);
            mcytLoader     = new MCYTLoader(Path.Combine(databasePath, "MCYT100.zip"), true);
            dutchLoader    = new SigComp11DutchLoader(Path.Combine(databasePath, "SigComp11_Dutch.zip"), true);
            chineseLoader  = new SigComp11ChineseLoader(Path.Combine(databasePath, "SigComp11Chinese.zip"), true);
            germanLoader   = new SigComp15GermanLoader(Path.Combine(databasePath, "SigWiComp2015_German.zip"), true);
            japaneseLoader = new SigComp13JapaneseLoader(Path.Combine(databasePath, "SigWiComp2013_Japanese.zip"), true);

            //labor:
            //svcLoader = new Svc2004Loader(@"Task2.zip", true);
            //mcytLoader = new MCYTLoader(@"MCYT_Signature_100.zip", true);
            //dutchLoader = new SigComp11DutchLoader(@"dutch_renamed.zip", true);


            Sampler sampler1 = null;
            Sampler sampler2 = null;
            Sampler sampler3 = null;
            Sampler sampler4 = null;


            VerifierBenchmark b = new VerifierBenchmark();

            switch (config.Database)
            {
            case "SVC2004":
                b.Loader = svcLoader;
                sampler1 = first10Sampler;
                sampler2 = last10Sampler;
                sampler3 = even10Sampler;
                sampler4 = odd10Sampler;
                break;

            case "MCYT100":
                b.Loader = mcytLoader;
                sampler1 = first10Sampler;
                sampler2 = last10Sampler;
                sampler3 = even10Sampler;
                sampler4 = odd10Sampler;
                break;

            case "DUTCH":
                b.Loader = dutchLoader;
                sampler1 = first10Sampler;
                sampler2 = last10Sampler;
                sampler3 = even10Sampler;
                sampler4 = odd10Sampler;
                break;

            case "GERMAN":
                b.Loader = germanLoader;
                sampler1 = first10Sampler;
                sampler2 = last10Sampler;
                sampler3 = even10Sampler;
                sampler4 = odd10Sampler;
                break;

            case "CHINESE":
                b.Loader = chineseLoader;
                sampler1 = first10Sampler;
                sampler2 = last10Sampler;
                sampler3 = even10Sampler;
                sampler4 = odd10Sampler;
                break;

            case "JAPANESE":
                b.Loader = japaneseLoader;
                sampler1 = first10Sampler;
                sampler2 = last10Sampler;
                sampler3 = even10Sampler;
                sampler4 = odd10Sampler;
                break;

            default:
                throw new NotSupportedException();
            }

            switch (config.Sampling)
            {
            case "S1":
                b.Sampler = sampler1;
                break;

            case "S2":
                b.Sampler = sampler2;
                break;

            case "S3":
                b.Sampler = sampler3;
                break;

            case "S4":
                b.Sampler = sampler4;
                break;

            default:
                break;
            }


            var pipeline = new SequentialTransformPipeline();

            //Filter first
            switch (config.ResamplingType_Filter)
            {
            case "P":
            case "P_FillPenUp":
                pipeline.Add(filterPoints);
                break;

            case "None":
            default:
                break;
            }

            if (config.Rotation)
            {
                pipeline.Add(normalizeRotation);
            }

            switch (config.Translation_Scaling.Translation)
            {
            case "CogToOriginX":
                pipeline.Add(cxTranslate);
                break;

            case "CogToOriginY":
                pipeline.Add(cyTranslate);
                break;

            case "CogToOriginXY":
                pipeline.Add(cxTranslate);
                pipeline.Add(cyTranslate);
                break;

            case "BottomLeftToOrigin":
                pipeline.Add(blxTranslate);
                pipeline.Add(blyTranslate);
                break;

            case "None":
            default:
                break;
            }

            switch (config.Translation_Scaling.Scaling)
            {
            case "X01":
                pipeline.Add(xScale);
                if (config.Features.Contains("P"))
                {
                    pipeline.Add(pScale);
                }
                break;

            case "Y01":
                pipeline.Add(yScale);
                if (config.Features.Contains("P"))
                {
                    pipeline.Add(pScale);
                }
                break;

            case "P01":
                pipeline.Add(pScale);
                break;

            case "X01Y01":
                pipeline.Add(xScale);
                pipeline.Add(yScale);
                pipeline.Add(pScale);
                break;

            case "X01Y0prop":
                pipeline.Add(xyUniformScale);
                if (config.Features.Contains("P"))
                {
                    pipeline.Add(pScale);
                }
                break;

            case "Y01X0prop":
                pipeline.Add(yxUniformScale);
                if (config.Features.Contains("P"))
                {
                    pipeline.Add(pScale);
                }
                break;

            case "None":
                if (config.Features.Contains("P"))
                {
                    pipeline.Add(pRelativeScale);
                }
                break;

            default:
                break;
            }

            Type ip;

            switch (config.Interpolation)
            {
            case "Cubic":
                ip = typeof(CubicInterpolation);
                break;

            case "Linear":
            default:
                ip = typeof(LinearInterpolation);
                break;
            }

            var featurelist = new List <FeatureDescriptor <List <double> > >()
            {
                Features.X, Features.Y, Features.Pressure, Features.Azimuth, Features.Altitude
            };

            //resample after transformations
            switch (config.ResamplingType_Filter)
            {
            case "SampleCount":
                pipeline.Add(new ResampleSamplesCountBased()
                {
                    InputFeatures     = featurelist,
                    OutputFeatures    = featurelist,
                    OriginalTFeature  = Features.T,
                    ResampledTFeature = Features.T,
                    NumOfSamples      = (int)config.ResamplingParam,
                    InterpolationType = ip
                });
                break;

            case "P_FillPenUp":
            case "FillPenUp":
                pipeline.Add(new FillPenUpDurations()
                {
                    InputFeatures     = featurelist,
                    OutputFeatures    = featurelist,
                    TimeInputFeature  = Features.T,
                    TimeOutputFeature = Features.T,
                    InterpolationType = ip
                });
                break;

            case "None":
            default:
                break;
            }

            var ClassifierFeatures = new List <FeatureDescriptor>();

            switch (config.Features)
            {
            case "X":
                ClassifierFeatures.Add(Features.X);
                break;

            case "XP":
                ClassifierFeatures.Add(Features.X);
                ClassifierFeatures.Add(Features.Pressure);
                break;

            case "Y":
                ClassifierFeatures.Add(Features.Y);
                break;

            case "YP":
                ClassifierFeatures.Add(Features.Y);
                ClassifierFeatures.Add(Features.Pressure);
                break;

            case "P":
                ClassifierFeatures.Add(Features.Pressure);
                break;

            case "Azimuth":
                ClassifierFeatures.Add(Features.Azimuth);
                break;

            case "Altitude":
                ClassifierFeatures.Add(Features.Altitude);
                break;

            case "XY":
                ClassifierFeatures.Add(Features.X);
                ClassifierFeatures.Add(Features.Y);
                break;

            case "XYP":
                ClassifierFeatures.Add(Features.X);
                ClassifierFeatures.Add(Features.Y);
                ClassifierFeatures.Add(Features.Pressure);
                break;

            case "XYPAzimuthAltitude":
                ClassifierFeatures.Add(Features.X);
                ClassifierFeatures.Add(Features.Y);
                ClassifierFeatures.Add(Features.Pressure);
                ClassifierFeatures.Add(Features.Azimuth);
                ClassifierFeatures.Add(Features.Altitude);
                break;

            default:
                break;
            }

            Func <double[], double[], double> distance = null;

            switch (config.Distance)
            {
            case "Euclidean":
                distance = Accord.Math.Distance.Euclidean;
                break;

            case "Manhattan":
                distance = Accord.Math.Distance.Manhattan;
                break;

            default:
                break;
            }
            IClassifier classifier;

            if (config.Classifier == "Dtw")
            {
                classifier = new DtwClassifier(distance);
                (classifier as DtwClassifier).Features = ClassifierFeatures;
            }
            else if (config.Classifier == "OptimalDtw")
            {
                classifier = new OptimalDtwClassifier(distance)
                {
                    Features = ClassifierFeatures,
                    Sampler  = b.Sampler
                };
            }
            else
            {
                throw new NotSupportedException();
            }

            b.Verifier = new Model.Verifier()
            {
                Pipeline   = pipeline,
                Classifier = classifier
            };

            b.Parameters = config.ToKeyValuePairs().ToList();

            return(b);
        }
Beispiel #22
0
        // Load Chart button
        private void button1_Click(object sender, EventArgs e)
        {
            Sampler sampler = initialConfig ? initialSampler : reconfigSampler;

            /*
             * sampler = DemoLib.PerformReadsWritesSyncs(sampler);
             * if (initialConfig)
             *  initialSampler = sampler;
             * else
             *  reconfigSampler = sampler;
             */

            this.chart1.Series["Latency"].Points.Clear();
            this.chart1.Series["Primary hit rate"].Points.Clear();
            this.chart1.Legends["Latency"].Enabled = true;

            if (enableHitRate)
            {
                this.chart1.Series["Primary hit rate"].IsVisibleInLegend = true;
            }
            else
            {
                this.chart1.Series["Primary hit rate"].IsVisibleInLegend = false;
            }

            this.chart1.Series["Latency"].Points.AddXY("Strong", sampler.GetSampleValue("strongLatency"));
            if (enableHitRate)
            {
                float primaryHitRate = (sampler.GetSampleValue("strongPrimaryAccesses") * 100) / sampler.GetSampleValue("strongTotalAccesses");
                this.chart1.Series["Primary hit rate"].Points.AddXY("Strong", primaryHitRate);
            }

            this.chart1.Series["Latency"].Points.AddXY("Causal", sampler.GetSampleValue("causalLatency"));
            if (enableHitRate)
            {
                float primaryHitRate = (sampler.GetSampleValue("causalPrimaryAccesses") * 100) / sampler.GetSampleValue("causalTotalAccesses");
                this.chart1.Series["Primary hit rate"].Points.AddXY("Causal", primaryHitRate);
            }

            this.chart1.Series["Latency"].Points.AddXY("Bounded", sampler.GetSampleValue("boundedLatency"));
            if (enableHitRate)
            {
                float primaryHitRate = (sampler.GetSampleValue("boundedPrimaryAccesses") * 100) / sampler.GetSampleValue("boundedTotalAccesses");
                this.chart1.Series["Primary hit rate"].Points.AddXY("Bounded", primaryHitRate);
            }

            this.chart1.Series["Latency"].Points.AddXY("Read my writes", sampler.GetSampleValue("readmywritesLatency"));
            if (enableHitRate)
            {
                float primaryHitRate = (sampler.GetSampleValue("readmywritesPrimaryAccesses") * 100) / sampler.GetSampleValue("readmywritesTotalAccesses");
                this.chart1.Series["Primary hit rate"].Points.AddXY("Read my writes", primaryHitRate);
            }

            this.chart1.Series["Latency"].Points.AddXY("Monotonic", sampler.GetSampleValue("monotonicLatency"));
            if (enableHitRate)
            {
                float primaryHitRate = (sampler.GetSampleValue("monotonicPrimaryAccesses") * 100) / sampler.GetSampleValue("monotonicTotalAccesses");
                this.chart1.Series["Primary hit rate"].Points.AddXY("Monotonic", primaryHitRate);
            }

            this.chart1.Series["Latency"].Points.AddXY("Eventual", sampler.GetSampleValue("eventualLatency"));
            if (enableHitRate)
            {
                float primaryHitRate = (sampler.GetSampleValue("eventualPrimaryAccesses") * 100) / sampler.GetSampleValue("eventualTotalAccesses");
                this.chart1.Series["Primary hit rate"].Points.AddXY("Eventual", primaryHitRate);
            }
        }
Beispiel #23
0
 public void Set_Sampler(int numSamples, float exp)
 {
     sampler_ptr = new Jittered(numSamples);
     this.exp    = exp;
     sampler_ptr.map_samples_to_hemisphere(exp);
 }
Beispiel #24
0
    /// <summary>
    /// Initialize the device objects
    /// </summary>
    /// <param name="dev">The grpahics device used to initialize</param>
    public void InitializeDeviceObjects(Device dev)
    {
        if (dev != null)
        {
            // Set up our events
            dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }

        // Keep a local copy of the device
        device        = dev;
        textureState0 = device.TextureState[0];
        textureState1 = device.TextureState[1];
        samplerState0 = device.SamplerState[0];
        renderState   = device.RenderState;

        // Establish the font and texture size
        textureScale = 1.0f;  // Draw fonts into texture without scaling

        // Large fonts need larger textures
        if (ourFontHeight > 60)
        {
            textureWidth = textureHeight = 2048;
        }
        else if (ourFontHeight > 30)
        {
            textureWidth = textureHeight = 1024;
        }
        else if (ourFontHeight > 15)
        {
            textureWidth = textureHeight = 512;
        }
        else
        {
            textureWidth = textureHeight = 256;
        }

        // If requested texture is too big, use a smaller texture and smaller font,
        // and scale up when rendering.
        Direct3D.Caps d3dCaps = device.DeviceCaps;

        if (textureWidth > d3dCaps.MaxTextureWidth)
        {
            textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
            textureWidth = textureHeight = d3dCaps.MaxTextureWidth;
        }

        Bitmap   bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g   = Graphics.FromImage(bmp);

        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;


        string str;
        float  x    = 0;
        float  y    = 0;
        Point  p    = new Point(0, 0);
        Size   size = new Size(0, 0);

        // Calculate the spacing between characters based on line height
        size = g.MeasureString(" ", systemFont).ToSize();
        x    = spacingPerChar = (int)Math.Ceiling(size.Height * 0.3);

        for (char c = (char)32; c < (char)127; c++)
        {
            str = c.ToString();
            // We need to do some things here to get the right sizes.  The default implemententation of MeasureString
            // will return a resolution independant size.  For our height, this is what we want.  However, for our width, we
            // want a resolution dependant size.
            Size resSize = g.MeasureString(str, systemFont).ToSize();
            size.Height = resSize.Height + 1;

            // Now the Resolution independent width
            if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats
            {
                resSize    = g.MeasureString(str, systemFont, p, StringFormat.GenericTypographic).ToSize();
                size.Width = resSize.Width;
            }
            else
            {
                size.Width = resSize.Width;
            }

            if ((x + size.Width + spacingPerChar) > textureWidth)
            {
                x  = spacingPerChar;
                y += size.Height;
            }

            if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats
            {
                g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y), StringFormat.GenericTypographic);
            }
            else
            {
                g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y));
            }
            textureCoords[c - 32, 0] = ((float)(x + 0 - spacingPerChar)) / textureWidth;
            textureCoords[c - 32, 1] = ((float)(y + 0 + 0)) / textureHeight;
            textureCoords[c - 32, 2] = ((float)(x + size.Width + spacingPerChar)) / textureWidth;
            textureCoords[c - 32, 3] = ((float)(y + size.Height + 0)) / textureHeight;

            x += size.Width + (2 * spacingPerChar);
        }

        // Create a new texture for the font from the bitmap we just created
        fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
        RestoreDeviceObjects(null, null);
    }
Beispiel #25
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Sampler obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Beispiel #26
0
        public ImportResult Import(GLTFAccessor.ImportResult[] accessors, GLTFNode.ImportResult[] nodes)
        {
            ImportResult result = new ImportResult();

            result.clip      = new AnimationClip();
            result.clip.name = name;

            for (int i = 0; i < channels.Length; i++)
            {
                Channel channel = channels[i];
                if (samplers.Length <= channel.sampler)
                {
                    Debug.LogWarning("Animation channel points to sampler at index " + channel.sampler + " which doesn't exist. Skipping animation clip.");
                    continue;
                }
                Sampler sampler = samplers[channel.sampler];

                string relativePath = "";

                GLTFNode.ImportResult node = nodes[channel.target.node.Value];
                while (node != null && !node.IsRoot)
                {
                    if (string.IsNullOrEmpty(relativePath))
                    {
                        relativePath = node.transform.name;
                    }
                    else
                    {
                        relativePath = node.transform.name + "/" + relativePath;
                    }

                    if (node.parent.HasValue)
                    {
                        node = nodes[node.parent.Value];
                    }
                    else
                    {
                        node = null;
                    }
                }

                float[] keyframeInput = accessors[sampler.input].ReadFloat().ToArray();
                switch (channel.target.path)
                {
                case "translation":
                    Vector3[]      pos  = accessors[sampler.output].ReadVec3().ToArray();
                    AnimationCurve posX = new AnimationCurve();
                    AnimationCurve posY = new AnimationCurve();
                    AnimationCurve posZ = new AnimationCurve();
                    for (int k = 0; k < keyframeInput.Length; k++)
                    {
                        posX.AddKey(keyframeInput[k], pos[k].x);
                        posY.AddKey(keyframeInput[k], pos[k].y);
                        posZ.AddKey(keyframeInput[k], -pos[k].z);
                    }
                    result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ);
                    break;

                case "rotation":
                    Vector4[]      rot  = accessors[sampler.output].ReadVec4().ToArray();
                    AnimationCurve rotX = new AnimationCurve();
                    AnimationCurve rotY = new AnimationCurve();
                    AnimationCurve rotZ = new AnimationCurve();
                    AnimationCurve rotW = new AnimationCurve();
                    for (int k = 0; k < keyframeInput.Length; k++)
                    {
                        rotX.AddKey(keyframeInput[k], rot[k].x);
                        rotY.AddKey(keyframeInput[k], rot[k].y);
                        rotZ.AddKey(keyframeInput[k], -rot[k].z);
                        rotW.AddKey(keyframeInput[k], -rot[k].w);
                    }
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW);
                    break;

                case "scale":
                    Vector3[]      scale  = accessors[sampler.output].ReadVec3().ToArray();
                    AnimationCurve scaleX = new AnimationCurve();
                    AnimationCurve scaleY = new AnimationCurve();
                    AnimationCurve scaleZ = new AnimationCurve();
                    for (int k = 0; k < keyframeInput.Length; k++)
                    {
                        scaleX.AddKey(keyframeInput[k], scale[k].x);
                        scaleY.AddKey(keyframeInput[k], scale[k].y);
                        scaleZ.AddKey(keyframeInput[k], scale[k].z);
                    }
                    result.clip.SetCurve(relativePath, typeof(Transform), "localScale.x", scaleX);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localScale.y", scaleY);
                    result.clip.SetCurve(relativePath, typeof(Transform), "localScale.z", scaleZ);
                    break;

                case "weights":
                    Debug.LogWarning("morph weights not supported");
                    break;
                }
            }
            return(result);
        }
Beispiel #27
0
        public void InitializeDeviceObjects(Device dev)
        {
            if (dev != null)
            {
                // Set up our events
                dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
            }

            // Keep a local copy of the device
            device = dev;
            textureState0 = device.TextureState[0];
            textureState1 = device.TextureState[1];
            samplerState0 = device.SamplerState[0];
            renderState = device.RenderState;

            // Create a bitmap on which to measure the alphabet
            Bitmap bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(bmp);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
            g.TextContrast = 0;

            // Establish the font and texture size
            textureScale  = 1.0f; // Draw fonts into texture without scaling

            // Calculate the dimensions for the smallest power-of-two texture which
            // can hold all the printable characters
            textureWidth = textureHeight = 128;
            for (;;)
            {
                try
                {
                    // Measure the alphabet
                    PaintAlphabet(g, true);
                }
                catch (System.InvalidOperationException)
                {
                    // Scale up the texture size and try again
                    textureWidth *= 2;
                    textureHeight *= 2;
                    continue;
                }

                break;
            }

            // If requested texture is too big, use a smaller texture and smaller font,
            // and scale up when rendering.
            Caps d3dCaps = device.DeviceCaps;

            // If the needed texture is too large for the video card...
            if (textureWidth > d3dCaps.MaxTextureWidth)
            {
                // Scale the font size down to fit on the largest possible texture
                textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
                textureWidth = textureHeight = d3dCaps.MaxTextureWidth;

                for(;;)
                {
                    // Create a new, smaller font
                    fontSize = (int) Math.Floor(fontSize * textureScale);
                    font = new System.Drawing.Font(font.Name, fontSize, font.Style);

                    try
                    {
                        // Measure the alphabet
                        PaintAlphabet(g, true);
                    }
                    catch (System.InvalidOperationException)
                    {
                        // If that still doesn't fit, scale down again and continue
                        textureScale *= 0.9F;
                        continue;
                    }

                    break;
                }
            }

            // Release the bitmap used for measuring and create one for drawing
            bmp.Dispose();
            bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            g = Graphics.FromImage(bmp);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.TextContrast = 0;

            // Draw the alphabet
            PaintAlphabet(g, false);

            // Create a new texture for the font from the bitmap we just created
            fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
            RestoreDeviceObjects(null, null);
        }
Beispiel #28
0
        public BloomCombinePS()
        {
            Name             = "BloomCombinePS";
            Type             = ShaderType.Pixel;
            KeyPart          = new TechniqueKey(ps: PixelShaderFlags.Diffuse | PixelShaderFlags.DiffuseMap);
            FeatureLevel     = FeatureLevel.PS_4_0_Level_9_1;
            EnableSeparators = true;
            var inputStruct = SpriteVS.VSOut;

            inputStruct.Name = "input";

            InputStruct  = inputStruct;
            OutputStruct = Struct.PixelShaderOutput;
            Texture tDiffuse = Texture.Diffuse;
            Texture tBloom   = new Texture()
            {
                Name = "tBloom", Type = Shaders.Type.Texture2D
            };
            Sampler sLinearWrap = Sampler.MinMagMipLinearWrap;
            var     cbFrame     = CBFrame;

            var blurParams = (Struct)cbFrame[0];

            Add(sLinearWrap);
            Add(tDiffuse);
            Add(tBloom);
            Add(cbFrame);

            TextureSampleNode nTexSample = new TextureSampleNode
            {
                Coordinates = new ReferenceNode {
                    Value = InputStruct[Param.SemanticVariables.Texture]
                },
                Texture   = tDiffuse,
                Sampler   = sLinearWrap,
                IsVerbose = true,
                Output    = new Vector {
                    Name = "cDiffuse", Type = Shaders.Type.Float4
                },
            };

            TextureSampleNode nBloomSample = new TextureSampleNode
            {
                Coordinates = new ReferenceNode {
                    Value = InputStruct[Param.SemanticVariables.Texture]
                },
                Texture   = tBloom,
                Sampler   = sLinearWrap,
                IsVerbose = true,
                Output    = new Vector {
                    Name = "cBloom", Type = Shaders.Type.Float4
                }
            };

            var mAdjustSaturation = new AdjustSaturation();

            FunctionNode nAdjustBloomSaturation = new FunctionNode()
            {
                Inputs = new List <INode>()
                {
                    nBloomSample,
                    new ReferenceNode()
                    {
                        Value = blurParams[Param.Floats.BloomSaturation]
                    }
                },
                Method     = mAdjustSaturation,
                ReturnType = Shaders.Type.Float4
            };

            FunctionNode nAdjustBaseSaturation = new FunctionNode()
            {
                Inputs = new List <INode>()
                {
                    nTexSample,
                    new ReferenceNode()
                    {
                        Value = blurParams[Param.Floats.BloomBaseSaturation]
                    }
                },
                Method     = mAdjustSaturation,
                ReturnType = Shaders.Type.Float4
            };

            MultiplyNode nMulBloom = new MultiplyNode()
            {
                Input1 = nAdjustBloomSaturation,
                Input2 = new ReferenceNode()
                {
                    Value = blurParams[Param.Floats.BloomIntensity]
                },
                Output    = nBloomSample.Output,
                IsVerbose = true,
                Declare   = false
            };
            MultiplyNode nMulBase = new MultiplyNode()
            {
                Input1 = nAdjustBaseSaturation,
                Input2 = new ReferenceNode()
                {
                    Value = blurParams[Param.Floats.BloomBaseIntensity]
                },
                Output    = nTexSample.Output,
                IsVerbose = true,
                Declare   = false
            };

            MultiplyNode nDarken = new MultiplyNode()
            {
                Input1 = nMulBase,
                Input2 = new SubtractionNode()
                {
                    Input1 = new ScalarNode()
                    {
                        Value = 1
                    },
                    Input2 = new UnaryFunctionNode()
                    {
                        Input1 = nMulBloom, Function = HlslIntrinsics.Saturate
                    },
                    Parenthesize = true
                },
                Output         = nTexSample.Output,
                IsVerbose      = true,
                Declare        = false,
                AssignToInput1 = true
            };

            Result = new PSOutputNode
            {
                FinalColor = new AdditionNode()
                {
                    Input1 = nDarken, Input2 = nMulBloom
                },
                Output = OutputStruct
            };
        }
Beispiel #29
0
 private void OnDestroy()
 {
     this.movement = null;
 }
Beispiel #30
0
        public override Spectrum Li(RayDifferential ray, Scene scene, Camera camera, Sampler sampler, int depth = 0)
        {
            var r = Random.Shared.NextSingle();

            return(new Spectrum(r));
        }
Beispiel #31
0
        internal Transaction(
            IApmLogger logger,
            string name,
            string type,
            Sampler sampler,
            DistributedTracingData distributedTracingData,
            IPayloadSender sender,
            IConfigSnapshot configSnapshot,
            ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer
            )
        {
            ConfigSnapshot = configSnapshot;
            Timestamp      = TimeUtils.TimestampNow();
            var idBytes = new byte[8];

            Id      = RandomGenerator.GenerateRandomBytesAsString(idBytes);
            _logger = logger?.Scoped($"{nameof(Transaction)}.{Id}");

            _sender = sender;
            _currentExecutionSegmentsContainer = currentExecutionSegmentsContainer;

            Name          = name;
            HasCustomName = false;
            Type          = type;

            var isSamplingFromDistributedTracingData = false;

            if (distributedTracingData == null)
            {
                var traceIdBytes = new byte[16];
                TraceId   = RandomGenerator.GenerateRandomBytesAsString(traceIdBytes);
                IsSampled = sampler.DecideIfToSample(idBytes);
            }
            else
            {
                TraceId   = distributedTracingData.TraceId;
                ParentId  = distributedTracingData.ParentId;
                IsSampled = distributedTracingData.FlagRecorded;
                isSamplingFromDistributedTracingData = true;
                _traceState = distributedTracingData.TraceState;
            }

            SpanCount = new SpanCount();

            _currentExecutionSegmentsContainer.CurrentTransaction = this;

            if (isSamplingFromDistributedTracingData)
            {
                _logger.Trace()
                ?.Log("New Transaction instance created: {Transaction}. " +
                      "IsSampled ({IsSampled}) is based on incoming distributed tracing data ({DistributedTracingData})." +
                      " Start time: {Time} (as timestamp: {Timestamp})",
                      this, IsSampled, distributedTracingData, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp);
            }
            else
            {
                _logger.Trace()
                ?.Log("New Transaction instance created: {Transaction}. " +
                      "IsSampled ({IsSampled}) is based on the given sampler ({Sampler})." +
                      " Start time: {Time} (as timestamp: {Timestamp})",
                      this, IsSampled, sampler, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp);
            }
        }
Beispiel #32
0
 public DummyIntegrator(Sampler sampler)
     : base(sampler)
 {
 }
        public static ShaderData CreateGLSL(byte[] byteCode, bool isVertexShader, List <ConstantBufferData> cbuffers, int sharedIndex, Dictionary <string, SamplerStateInfo> samplerStates, bool debug)
        {
            var dxshader = new ShaderData(isVertexShader, sharedIndex, byteCode);

            // Use MojoShader to convert the HLSL bytecode to GLSL.

            var parseDataPtr = MojoShader.NativeMethods.MOJOSHADER_parse(
                "glsl",
                byteCode,
                byteCode.Length,
                IntPtr.Zero,
                0,
                IntPtr.Zero,
                0,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero);

            var parseData = MarshalHelper.Unmarshal <MojoShader.MOJOSHADER_parseData> (parseDataPtr);

            if (parseData.error_count > 0)
            {
                var errors = MarshalHelper.UnmarshalArray <MojoShader.MOJOSHADER_error> (
                    parseData.errors,
                    parseData.error_count
                    );
                throw new Exception(errors [0].error);
            }

            // Conver the attributes.
            //
            // TODO: Could this be done using DX shader reflection?
            //
            {
                var attributes = MarshalHelper.UnmarshalArray <MojoShader.MOJOSHADER_attribute> (
                    parseData.attributes, parseData.attribute_count);

                dxshader._attributes = new Attribute[attributes.Length];
                for (var i = 0; i < attributes.Length; i++)
                {
                    dxshader._attributes [i].name  = attributes [i].name;
                    dxshader._attributes [i].index = attributes [i].index;
                    dxshader._attributes [i].usage = EffectObject.ToXNAVertexElementUsage(attributes [i].usage);
                }
            }

            var symbols = MarshalHelper.UnmarshalArray <MojoShader.MOJOSHADER_symbol> (
                parseData.symbols, parseData.symbol_count);

            //try to put the symbols in the order they are eventually packed into the uniform arrays
            //this /should/ be done by pulling the info from mojoshader
            Array.Sort(symbols, delegate(MojoShader.MOJOSHADER_symbol a, MojoShader.MOJOSHADER_symbol b) {
                uint va = a.register_index;
                if (a.info.elements == 1)
                {
                    va += 1024;                     //hax. mojoshader puts array objects first
                }
                uint vb = b.register_index;
                if (b.info.elements == 1)
                {
                    vb += 1024;
                }
                return(va.CompareTo(vb));
            }
                       ); //(a, b) => ((int)(a.info.elements > 1))a.register_index.CompareTo(b.register_index));

            // NOTE: It seems the latest versions of MojoShader only
            // output vec4 register sets.  We leave the code below, but
            // the runtime has been optimized for this case.

            // For whatever reason the register indexing is
            // incorrect from MojoShader.
            {
                uint bool_index   = 0;
                uint float4_index = 0;
                uint int4_index   = 0;

                for (var i = 0; i < symbols.Length; i++)
                {
                    switch (symbols [i].register_set)
                    {
                    case MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_BOOL:
                        symbols [i].register_index = bool_index;
                        bool_index += symbols [i].register_count;
                        break;

                    case MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_FLOAT4:
                        symbols [i].register_index = float4_index;
                        float4_index += symbols[i].register_count;
                        break;

                    case MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_INT4:
                        symbols [i].register_index = int4_index;
                        int4_index += symbols [i].register_count;
                        break;
                    }
                }
            }

            // Get the samplers.
            var samplers = MarshalHelper.UnmarshalArray <MojoShader.MOJOSHADER_sampler> (
                parseData.samplers, parseData.sampler_count);

            dxshader._samplers = new Sampler[samplers.Length];
            for (var i = 0; i < samplers.Length; i++)
            {
                // We need the original sampler name... look for that in the symbols.
                var originalSamplerName =
                    symbols.First(e => e.register_set == MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_SAMPLER &&
                                  e.register_index == samplers[i].index
                                  ).name;

                var sampler = new Sampler
                {
                    //sampler mapping to parameter is unknown atm
                    parameter = -1,

                    // GLSL needs the MojoShader mangled sampler name.
                    samplerName = samplers[i].name,

                    // By default use the original sampler name for the parameter name.
                    parameterName = originalSamplerName,

                    textureSlot = samplers[i].index,
                    samplerSlot = samplers[i].index,
                    type        = samplers[i].type,
                };

                SamplerStateInfo state;
                if (samplerStates.TryGetValue(originalSamplerName, out state))
                {
                    sampler.state         = state.State;
                    sampler.parameterName = state.TextureName ?? originalSamplerName;
                }

                // Store the sampler.
                dxshader._samplers[i] = sampler;
            }

            // Gather all the parameters used by this shader.
            var symbol_types = new [] {
                new { name = dxshader.IsVertexShader ? "vs_uniforms_bool" : "ps_uniforms_bool", set = MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_BOOL, },
                new { name = dxshader.IsVertexShader ? "vs_uniforms_ivec4" : "ps_uniforms_ivec4", set = MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_INT4, },
                new { name = dxshader.IsVertexShader ? "vs_uniforms_vec4" : "ps_uniforms_vec4", set = MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_FLOAT4, },
            };

            var cbuffer_index = new List <int> ();

            for (var i = 0; i < symbol_types.Length; i++)
            {
                var cbuffer = new ConstantBufferData(symbol_types [i].name,
                                                     symbol_types [i].set,
                                                     symbols);
                if (cbuffer.Size == 0)
                {
                    continue;
                }

                var match = cbuffers.FindIndex(e => e.SameAs(cbuffer));
                if (match == -1)
                {
                    cbuffer_index.Add(cbuffers.Count);
                    cbuffers.Add(cbuffer);
                }
                else
                {
                    cbuffer_index.Add(match);
                }
            }
            dxshader._cbuffers = cbuffer_index.ToArray();

            var glslCode = parseData.output;

            // TODO: This sort of sucks... why does MojoShader not produce
            // code valid for GLES out of the box?

            // GLES platforms do not like this.
            glslCode = glslCode.Replace("#version 110", "");

            // Add the required precision specifiers for GLES.

            var floatPrecision = dxshader.IsVertexShader ? "precision highp float;\r\n" : "precision mediump float;\r\n";

            glslCode = "#ifdef GL_ES\r\n" +
                       floatPrecision +
                       "precision mediump int;\r\n" +
                       "#endif\r\n" +
                       glslCode;

            // Enable standard derivatives extension as necessary
            if ((glslCode.IndexOf("dFdx", StringComparison.InvariantCulture) >= 0) ||
                (glslCode.IndexOf("dFdy", StringComparison.InvariantCulture) >= 0))
            {
                glslCode = "#extension GL_OES_standard_derivatives : enable\r\n" + glslCode;
            }

            // Store the code for serialization.
            dxshader.ShaderCode = Encoding.ASCII.GetBytes(glslCode);

            return(dxshader);
        }
Beispiel #34
0
        protected override void OnLoad()
        {
            base.OnLoad();
            // load texture from file
            using (var bitmap = new Bitmap("Data/Textures/checker.jpg"))
            {
                BitmapTexture.CreateCompatible(bitmap, out _texture);
                _texture.LoadBitmap(bitmap);
            }
            _texture.GenerateMipMaps();

            // initialize sampler
            _sampler = new Sampler();
            _sampler.SetWrapMode(TextureWrapMode.Repeat);

            // create vertex data for a big plane
            const int a        = 10;
            const int b        = 10;
            var       vertices = new[]
            {
                new Vertex(-a, 0, -a, 0, 0),
                new Vertex(a, 0, -a, b, 0),
                new Vertex(-a, 0, a, 0, b),
                new Vertex(a, 0, a, b, b)
            };

            // create buffer object and upload vertex data
            _vbo = new Buffer <Vertex>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // initialize shader
            _program = ProgramFactory.Create <SimpleTextureProgram>();
            // activate shader program
            _program.Use();
            // bind sampler
            _sampler.Bind(TextureUnit.Texture0);
            // bind texture
            _program.Texture.BindTexture(TextureUnit.Texture0, _texture);
            // which is equivalent to
            //_program.Texture.Set(TextureUnit.Texture0);
            //_texture.Bind(TextureUnit.Texture0);

            // set up vertex array and attributes
            _vao = new VertexArray();
            _vao.Bind();
            // memory layout of our data is XYZUVXYZUV...
            // the buffer abstraction knows the total size of one "pack" of vertex data
            // and if a vertex attribute is bound without further arguments the first N elements are taken from each pack
            // where N is provided via the VertexAttribAttribute on the program property:
            _vao.BindAttribute(_program.InPosition, _vbo);
            // if data should not be taken from the start of each pack, the offset must be given in bytes
            // to reach the texture coordinates UV the XYZ coordinates must be skipped, that is 3 floats, i.e. an offset of 12 bytes is needed
            _vao.BindAttribute(_program.InTexCoord, _vbo, 12);
            // if needed all the available arguments can be specified manually, e.g.
            //_vao.BindAttribute(_program.InTexCoord, _vbo, 2, VertexAttribPointerType.Float, Marshal.SizeOf(typeof(Vertex)), 12, false);

            // set default camera
            ActiveCamera.Position = new Vector3(0, 0.5f, 3);

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
Beispiel #35
0
        protected override void Serialize(UnityEngine.Object sourceAsset)
        {
            this.texture = sourceAsset as UnityEngine.Cubemap;
            //先把原始图片导出来
            this.ExportTexture();

            var path   = PathHelper.GetTexturePath(this.texture);
            var mipmap = this.texture.mipmapCount > 1;
            //
            {
                this._root.Images.Add(new Image()
                {
                    Uri = ExportSetting.instance.GetExportPath(path)
                });
            }
            //
            {
                var filterMode = this.texture.filterMode;
                var wrapMode   = this.texture.wrapMode;

                var sampler = new Sampler();
                this._root.Samplers.Add(sampler);
                if (wrapMode == TextureWrapMode.Repeat)
                {
                    sampler.WrapS = GLTF.Schema.WrapMode.Repeat;
                    sampler.WrapT = GLTF.Schema.WrapMode.Repeat;
                }
                else
                {
                    sampler.WrapS = GLTF.Schema.WrapMode.ClampToEdge;
                    sampler.WrapT = GLTF.Schema.WrapMode.ClampToEdge;
                }
                sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
                if (!mipmap)
                {
                    sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
                }
                else if (filterMode == FilterMode.Point)
                {
                    sampler.MinFilter = MinFilterMode.NearestMipmapNearest;
                }
                else if (filterMode == FilterMode.Bilinear)
                {
                    sampler.MinFilter = MinFilterMode.LinearMipmapNearest;
                }
                else if (filterMode == FilterMode.Trilinear)
                {
                    sampler.MinFilter = MinFilterMode.LinearMipmapLinear;
                }
            }
            //
            {
                var gltfTexture = new GLTF.Schema.Texture();
                this._root.Textures.Add(gltfTexture);

                gltfTexture.Sampler    = new SamplerId();
                gltfTexture.Source     = new ImageId();
                gltfTexture.Extensions = new Dictionary <string, IExtension>()
                {
                    {
                        TextureExtension.EXTENSION_NAME,
                        new TextureExtension()
                        {
                            anisotropy = this.texture.anisoLevel,
                            format     = GetTextureFormat(),
                            levels     = mipmap ? 0 : 1
                        }
                    }
                };
            }
        }
Beispiel #36
0
            public static IList<Star> GenerateStars(int count, float intensity, bool colorize, int seed)
            {
                Sampler sampler = new Sampler(seed);
                Random random = new Random(seed);
                var starPositions = sampler.GenerateJitteredSamples((int)Math.Sqrt(count)).ToList();
                List<Star> stars = new List<Star>(starPositions.Count());

                foreach (var starPosition in starPositions)
                {
                    Vector3 color = new Vector3(intensity, intensity, intensity);
                    if (colorize)
                    {
                        color = Vector3.Multiply(color, new Vector3(
                            (float)random.NextDouble(),
                            (float)random.NextDouble(),
                            (float)random.NextDouble()));
                    }
                    else
                    {
                        color = Vector3.Multiply(color, (float)random.NextDouble());
                    }
                    Vector2 position = new Vector2((float)starPosition.X, (float)starPosition.Y);
                    stars.Add(new Star() { Position = position, Color = color });
                }
                return stars;
            }
Beispiel #37
0
 public BRDF(Sampler sampler)
 {
     this.Sampler = sampler;
 }
 public void ReadSampler( XmlNode node, ColladaMeshInfo meshInfo )
 {
     // the spec shows the id attribute as optional,
     // but a sampler without an id is pointless
     // (cannot be referenced by a channel)
     string samplerId = node.Attributes[ "id" ].Value;
     Sampler sampler = new Sampler( samplerId );
     foreach( XmlNode childNode in node.ChildNodes )
     {
         switch( childNode.Name )
         {
         case "input":
             ReadSamplerInput( sampler, childNode, meshInfo );
             break;
         default:
             DebugMessage( childNode );
             break;
         }
     }
     // TODO: Put the sampler in a dictionary
     if( sampler.Input == null || sampler.Output == null )
     {
         log.InfoFormat( "Ignoring incomplete sampler: {0}", samplerId );
         return;
     }
     meshInfo.Samplers[ sampler.SamplerId ] = sampler;
 }
Beispiel #39
0
        public static ShaderData CreateHLSL(byte[] byteCode, bool isVertexShader, List <ConstantBufferData> cbuffers, int sharedIndex, Dictionary <string, SamplerStateInfo> samplerStates, bool debug)
        {
            var dxshader = new ShaderData(isVertexShader, sharedIndex, byteCode);

            dxshader._attributes = new Attribute[0];

            // Strip the bytecode we're gonna save!
            var stripFlags = SharpDX.D3DCompiler.StripFlags.CompilerStripReflectionData |
                             SharpDX.D3DCompiler.StripFlags.CompilerStripTestBlobs;

            if (!debug)
            {
                stripFlags |= SharpDX.D3DCompiler.StripFlags.CompilerStripDebugInformation;
            }

            using (var original = new SharpDX.D3DCompiler.ShaderBytecode(byteCode))
            {
                // Strip the bytecode for saving to disk.
                var stripped = original.Strip(stripFlags);
                {
                    // Only SM4 and above works with strip... so this can return null!
                    if (stripped != null)
                    {
                        dxshader.ShaderCode = stripped;
                    }
                    else
                    {
                        // TODO: There is a way to strip SM3 and below
                        // but we have to write the method ourselves.
                        //
                        // If we need to support it then consider porting
                        // this code over...
                        //
                        // http://entland.homelinux.com/blog/2009/01/15/stripping-comments-from-shader-bytecodes/
                        //
                        dxshader.ShaderCode = (byte[])dxshader.Bytecode.Clone();
                    }
                }

                // Use reflection to get details of the shader.
                using (var refelect = new SharpDX.D3DCompiler.ShaderReflection(byteCode))
                {
                    // Get the samplers.
                    var samplers = new List <Sampler>();
                    for (var i = 0; i < refelect.Description.BoundResources; i++)
                    {
                        var rdesc = refelect.GetResourceBindingDescription(i);
                        if (rdesc.Type == SharpDX.D3DCompiler.ShaderInputType.Texture)
                        {
                            var samplerName = rdesc.Name;

                            var sampler = new Sampler
                            {
                                samplerName   = string.Empty,
                                textureSlot   = rdesc.BindPoint,
                                samplerSlot   = rdesc.BindPoint,
                                parameterName = samplerName
                            };

                            SamplerStateInfo state;
                            if (samplerStates.TryGetValue(samplerName, out state))
                            {
                                sampler.parameterName = state.TextureName ?? samplerName;
                                sampler.state         = state.State;
                            }
                            else
                            {
                                foreach (var s in samplerStates.Values)
                                {
                                    if (samplerName == s.TextureName)
                                    {
                                        sampler.state = s.State;
                                        samplerName   = s.Name;
                                        break;
                                    }
                                }
                            }

                            // Find sampler slot, which can be different from the texture slot.
                            for (int j = 0; j < refelect.Description.BoundResources; j++)
                            {
                                var samplerrdesc = refelect.GetResourceBindingDescription(j);

                                if (samplerrdesc.Type == SharpDX.D3DCompiler.ShaderInputType.Sampler &&
                                    samplerrdesc.Name == samplerName)
                                {
                                    sampler.samplerSlot = samplerrdesc.BindPoint;
                                    break;
                                }
                            }

                            switch (rdesc.Dimension)
                            {
                            case ShaderResourceViewDimension.Texture1D:
                            case ShaderResourceViewDimension.Texture1DArray:
                                sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_1D;
                                break;

                            case ShaderResourceViewDimension.Texture2D:
                            case ShaderResourceViewDimension.Texture2DArray:
                            case ShaderResourceViewDimension.Texture2DMultisampled:
                            case ShaderResourceViewDimension.Texture2DMultisampledArray:
                                sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_2D;
                                break;

                            case ShaderResourceViewDimension.Texture3D:
                                sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_VOLUME;
                                break;

                            case ShaderResourceViewDimension.TextureCube:
                            case ShaderResourceViewDimension.TextureCubeArray:
                                sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_CUBE;
                                break;
                            }

                            samplers.Add(sampler);
                        }
                    }
                    dxshader._samplers = samplers.ToArray();

                    // Gather all the constant buffers used by this shader.
                    dxshader._cbuffers = new int[refelect.Description.ConstantBuffers];
                    for (var i = 0; i < refelect.Description.ConstantBuffers; i++)
                    {
                        var cb = new ConstantBufferData(refelect.GetConstantBuffer(i));

                        // Look for a duplicate cbuffer in the list.
                        for (var c = 0; c < cbuffers.Count; c++)
                        {
                            if (cb.SameAs(cbuffers[c]))
                            {
                                cb = null;
                                dxshader._cbuffers[i] = c;
                                break;
                            }
                        }

                        // Add a new cbuffer.
                        if (cb != null)
                        {
                            dxshader._cbuffers[i] = cbuffers.Count;
                            cbuffers.Add(cb);
                        }
                    }
                }
            }

            return(dxshader);
        }
Beispiel #40
0
 public override void Setup(IRayDenLibraryFrame newFrame)
 {
     base.Setup(newFrame);
     samples = new Sample[SamplesPerIteration];
     sampler = new Sampler(Width, Height, SamplesPerPixel, (MaxRecursionLevel) * (ValuesPerVertex));
 }
Beispiel #41
0
 public void SetDiffSampler(Sampler sampler)
 {
     diffuse.Sampler = sampler;
 }
 public void SetSampler(Sampler s)
 {
     sampler = s;
     sampler.MapSamplesToHemisphere(1);
 }
Beispiel #43
0
 public unsafe void DestroySampler(Sampler sampler, AllocationCallbacks* allocator = null)
 {
     vkDestroySampler(this, sampler, allocator);
 }
Beispiel #44
0
 private static Func<int, IEnumerable<Vector2d>> GetUniformSampler()
 {
     Sampler sampler = new Sampler();
     return (sampleCount) => sampler.GenerateUniformPoints(sampleCount);
 }
 public void ReadSamplerInput( Sampler sampler, XmlNode node, ColladaMeshInfo meshInfo )
 {
     InputSourceCollection tmp = ReadInput( node, meshInfo );
     Debug.Assert( tmp.GetSources().Count == 1 );
     InputSource entry = tmp.GetSources()[ 0 ];
     switch( entry.Semantic )
     {
     case "INPUT":
         sampler.Input = entry;
         break;
     case "OUTPUT":
         sampler.Output = entry;
         break;
     case "INTERPOLATION":
         sampler.Interpolation = entry;
         break;
     default:
         log.WarnFormat( "Unhandled sampler semantic: {0}", entry.Semantic );
         break;
     }
 }
        public static ShaderData CreateHLSL(byte[] byteCode, bool isVertexShader, List<ConstantBufferData> cbuffers, int sharedIndex, Dictionary<string, SamplerStateInfo> samplerStates, bool debug)
        {
            var dxshader = new ShaderData();
            dxshader.IsVertexShader = isVertexShader;
            dxshader.SharedIndex = sharedIndex;
            dxshader.Bytecode = (byte[])byteCode.Clone();

            // Strip the bytecode we're gonna save!
            var stripFlags = SharpDX.D3DCompiler.StripFlags.CompilerStripReflectionData |
                             SharpDX.D3DCompiler.StripFlags.CompilerStripTestBlobs;

            if (!debug)
                stripFlags |= SharpDX.D3DCompiler.StripFlags.CompilerStripDebugInformation;

            using (var original = new SharpDX.D3DCompiler.ShaderBytecode(byteCode))
            {
                // Strip the bytecode for saving to disk.
                var stripped = original.Strip(stripFlags);
                {
                    // Only SM4 and above works with strip... so this can return null!
                    if (stripped != null)
                    {
                        dxshader.ShaderCode = stripped;
                    }
                    else
                    {
                        // TODO: There is a way to strip SM3 and below
                        // but we have to write the method ourselves.
                        // 
                        // If we need to support it then consider porting
                        // this code over...
                        //
                        // http://entland.homelinux.com/blog/2009/01/15/stripping-comments-from-shader-bytecodes/
                        //
                        dxshader.ShaderCode = (byte[])dxshader.Bytecode.Clone();
                    }
                }

                // Use reflection to get details of the shader.
                using (var refelect = new SharpDX.D3DCompiler.ShaderReflection(byteCode))
                {
                    // Get the samplers.
                    var samplers = new List<Sampler>();
                    for (var i = 0; i < refelect.Description.BoundResources; i++)
                    {
                        var rdesc = refelect.GetResourceBindingDescription(i);
                        if (rdesc.Type == SharpDX.D3DCompiler.ShaderInputType.Texture)
                        {
                            var samplerName = rdesc.Name;

                            var sampler = new Sampler
                            {
                                textureSlot = rdesc.BindPoint,
                                samplerSlot = rdesc.BindPoint,
                                parameterName = samplerName
                            };
                            
                            SamplerStateInfo state;
                            if (samplerStates.TryGetValue(samplerName, out state))
                            {
                                sampler.parameterName = state.TextureName ?? samplerName;
                                sampler.state = state.State;
                            }
                            else
                            {
                                foreach (var s in samplerStates.Values)
                                {
                                    if (samplerName == s.TextureName)
                                    {
                                        sampler.state = s.State;
                                        samplerName = s.Name;
                                        break;
                                    }
                                }
                            }

                            // Find sampler slot, which can be different from the texture slot.
                            for (int j = 0; j < refelect.Description.BoundResources; j++)
                            {
                                var samplerrdesc = refelect.GetResourceBindingDescription(j);

                                if (samplerrdesc.Type == SharpDX.D3DCompiler.ShaderInputType.Sampler && 
                                    samplerrdesc.Name == samplerName)
                                {
                                    sampler.samplerSlot = samplerrdesc.BindPoint;
                                    break;
                                }
                            }

                            switch (rdesc.Dimension)
                            {
                                case ShaderResourceViewDimension.Texture1D:
                                case ShaderResourceViewDimension.Texture1DArray:
                                    sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_1D;
                                    break;

                                case ShaderResourceViewDimension.Texture2D:
                                case ShaderResourceViewDimension.Texture2DArray:
                                case ShaderResourceViewDimension.Texture2DMultisampled:
                                case ShaderResourceViewDimension.Texture2DMultisampledArray:
                                    sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_2D;
                                    break;

                                case ShaderResourceViewDimension.Texture3D:
                                    sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_VOLUME;
                                    break;

                                case ShaderResourceViewDimension.TextureCube:
                                case ShaderResourceViewDimension.TextureCubeArray:
                                    sampler.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_CUBE;
                                    break;
                            }

                            samplers.Add(sampler);
                        }
                    }
                    dxshader._samplers = samplers.ToArray();

                    // Gather all the constant buffers used by this shader.
                    dxshader._cbuffers = new int[refelect.Description.ConstantBuffers];
                    for (var i = 0; i < refelect.Description.ConstantBuffers; i++)
                    {
                        var cb = new ConstantBufferData(refelect.GetConstantBuffer(i));

                        // Look for a duplicate cbuffer in the list.
                        for (var c = 0; c < cbuffers.Count; c++)
                        {
                            if (cb.SameAs(cbuffers[c]))
                            {
                                cb = null;
                                dxshader._cbuffers[i] = c;
                                break;
                            }
                        }

                        // Add a new cbuffer.
                        if (cb != null)
                        {
                            dxshader._cbuffers[i] = cbuffers.Count;
                            cbuffers.Add(cb);
                        }
                    }
                }
            }

            return dxshader;
        }
Beispiel #47
0
        public override void OnStart()
        {
            ComputeShader  = Graphics.Content.LoadShaderModule(Path.Combine("Sprites", "BasicSprites.comp.spv"));
            VertexShader   = Graphics.Content.LoadShaderModule(Path.Combine("Sprites", "BasicSprites.vert.spv"));
            FragmentShader = Graphics.Content.LoadShaderModule(Path.Combine("Sprites", "BasicSprites.frag.spv"));
            TextureSampler = Graphics.Device.CreateSampler(new SamplerCreateInfo
            {
                MinFilter = Filter.Linear,
                MagFilter = Filter.Linear
            });
            GraphicsDescriptorPool = Graphics.Device.CreateDescriptorPool(new DescriptorPoolCreateInfo(
                                                                              MaxSets, new DescriptorPoolSize[]
            {
                new DescriptorPoolSize(DescriptorType.UniformBuffer, MaxSets),
                new DescriptorPoolSize(DescriptorType.CombinedImageSampler, MaxSets),
                new DescriptorPoolSize(DescriptorType.UniformBuffer, MaxSets)
            },
                                                                              DescriptorPoolCreateFlags.FreeDescriptorSet
                                                                              ));
            ComputeDescriptorPool = Graphics.Device.CreateDescriptorPool(new DescriptorPoolCreateInfo(
                                                                             MaxSets, new DescriptorPoolSize[]
            {
                new DescriptorPoolSize(DescriptorType.StorageBuffer, MaxSets),
                new DescriptorPoolSize(DescriptorType.UniformBuffer, MaxSets),
                new DescriptorPoolSize(DescriptorType.UniformBuffer, MaxSets)
            },
                                                                             DescriptorPoolCreateFlags.FreeDescriptorSet
                                                                             ));
            GraphicsDescriptorSetLayout = Graphics.Device.CreateDescriptorSetLayout(new DescriptorSetLayoutCreateInfo(
                                                                                        new[]
            {
                new DescriptorSetLayoutBinding(
                    binding: 0,
                    descriptorType: DescriptorType.UniformBuffer,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Vertex
                    ),
                new DescriptorSetLayoutBinding(
                    binding: 1,
                    descriptorType: DescriptorType.CombinedImageSampler,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Fragment
                    ),
                new DescriptorSetLayoutBinding(
                    binding: 2,
                    descriptorType: DescriptorType.UniformBuffer,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Vertex
                    )
            }
                                                                                        ));
            ComputeDescriptorSetLayout = Graphics.Device.CreateDescriptorSetLayout(new DescriptorSetLayoutCreateInfo(
                                                                                       new[]
            {
                new DescriptorSetLayoutBinding(
                    binding: 0,
                    descriptorType: DescriptorType.StorageBuffer,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Compute
                    ),
                new DescriptorSetLayoutBinding(
                    binding: 1,
                    descriptorType: DescriptorType.StorageBuffer,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Compute
                    ),
                new DescriptorSetLayoutBinding(
                    binding: 2,
                    descriptorType: DescriptorType.UniformBuffer,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Compute
                    ),
                new DescriptorSetLayoutBinding(
                    binding: 3,
                    descriptorType: DescriptorType.UniformBuffer,
                    descriptorCount: 1,
                    stageFlags: ShaderStages.Compute
                    )
            }
                                                                                       ));
            GraphicsPipelineLayout = Graphics.Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(
                                                                              setLayouts: new[] { GraphicsDescriptorSetLayout }
                                                                              ));
            ComputePipelineLayout = Graphics.Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(
                                                                             setLayouts: new[] { ComputeDescriptorSetLayout }
                                                                             ));
            GraphicsPipeline = Graphics.Device.CreateGraphicsPipeline(new GraphicsPipelineCreateInfo(
                                                                          layout: GraphicsPipelineLayout,
                                                                          renderPass: RenderPass.RenderPass,
                                                                          subpass: 0,
                                                                          stages: new[]
            {
                new PipelineShaderStageCreateInfo(ShaderStages.Vertex, VertexShader, "main"),
                new PipelineShaderStageCreateInfo(ShaderStages.Fragment, FragmentShader, "main")
            },
                                                                          inputAssemblyState: new PipelineInputAssemblyStateCreateInfo(PrimitiveTopology.TriangleList),
                                                                          vertexInputState: new PipelineVertexInputStateCreateInfo(
                                                                              new VertexInputBindingDescription[]
            {
                new VertexInputBindingDescription(
                    0,
                    Interop.SizeOf <VertexInstance>(),
                    VertexInputRate.Instance
                    )
            },
                                                                              new VertexInputAttributeDescription[]
            {
                new VertexInputAttributeDescription(                 // Transform matrix row 0
                    0, 0, Format.R32G32B32A32SFloat, 0
                    ),
                new VertexInputAttributeDescription(                 // Transform matrix row 1
                    1, 0, Format.R32G32B32A32SFloat, 16
                    ),
                new VertexInputAttributeDescription(                 // Transform matrix row 2
                    2, 0, Format.R32G32B32A32SFloat, 32
                    ),
                new VertexInputAttributeDescription(                 // Transform matrix row 03
                    3, 0, Format.R32G32B32A32SFloat, 48
                    ),
                new VertexInputAttributeDescription(                 // Rectangle
                    4, 0, Format.R32G32B32A32SFloat, 64
                    )
            }
                                                                              ),
                                                                          rasterizationState: new PipelineRasterizationStateCreateInfo(
                                                                              polygonMode: PolygonMode.Fill,
                                                                              cullMode: CullModes.None,
                                                                              frontFace: FrontFace.Clockwise,
                                                                              lineWidth: 1f
                                                                              ),
                                                                          viewportState: new PipelineViewportStateCreateInfo(
                                                                              new Viewport(0f, 0f, Graphics.Window.Size.X, Graphics.Window.Size.Y),
                                                                              new Rect2D(0, 0, (int)Graphics.Window.Size.X, (int)Graphics.Window.Size.Y)
                                                                              ),
                                                                          multisampleState: new PipelineMultisampleStateCreateInfo(
                                                                              rasterizationSamples: SampleCounts.Count1,
                                                                              minSampleShading: 1
                                                                              ),
                                                                          colorBlendState: new PipelineColorBlendStateCreateInfo(
                                                                              attachments: new[]
            {
                BlendStates.AlphaPremultiplied
            }
                                                                              )
                                                                          ));
            ComputePipeline = Graphics.Device.CreateComputePipeline(new ComputePipelineCreateInfo(
                                                                        stage: new PipelineShaderStageCreateInfo(ShaderStages.Compute, ComputeShader, "main"),
                                                                        layout: ComputePipelineLayout,
                                                                        flags: PipelineCreateFlags.None
                                                                        ));
            CameraUniform = VKBuffer <CameraUniformBlock> .UniformBuffer(
                $"{nameof(SpriteEffect)}.{nameof(CameraUniform)}",
                Graphics,
                1
                );

            TimeUniform = VKBuffer <ListTime> .UniformBuffer(
                $"{nameof(SpriteEffect)}.{nameof(TimeUniform)}",
                Graphics,
                MaxSets
                );

            AnimationUniform = VKBuffer <Animation.ComputeInstruction> .UniformBuffer(
                $"{nameof(SpriteEffect)}.{nameof(AnimationUniform)}",
                Graphics,
                Animation.MaxInstructions *MaxSets
                );

            ComputeSemaphore = Graphics.Device.CreateSemaphore();
            SetCamera(Vector2.Zero, new Vector2(Graphics.Window.Size.X, -Graphics.Window.Size.Y));
        }
        //private IEnumerable<Vector2d> GenerateLensSamples(int tileSize, int sqrtSampleCount)
        //{
        //    int pixelCount = tileSize * tileSize;
        //    IEnumerator<Vector2d>[] jitteredSamplers = new IEnumerator<Vector2d>[pixelCount];
        //    Sampler sampler = new Sampler();
        //    for (int i = 0; i < pixelCount; i++)
        //    {
        //        jitteredSamplers[i] = sampler.GenerateJitteredSamples(MaxTotalSampleCount).GetEnumerator();
        //    }
        //    for (int sample = 0; sample < MaxTotalSampleCount; sample++)
        //    {
        //        for (int i = 0; i < pixelCount; i++)
        //        {
        //            jitteredSamplers[i].MoveNext();
        //            yield return jitteredSamplers[i].Current;
        //        }
        //    }
        //}
        private void GeneratePixelSamplesTexture(int textureId, int sqrtSampleCount, int sampleCount)
        {
            GL.BindTexture(TextureTarget.Texture1D, textureId);
            // size of a group of samples for a single pixel
            int bands = 2;
            int textureSize = bands * sampleCount;

            Sampler sampler = new Sampler();
            IntPtr texturePtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Half)) * textureSize);
            unsafe
            {
                Half* row = (Half*)texturePtr;
                int index = 0;
                foreach (Vector2d sample in sampler.GenerateJitteredSamples(sqrtSampleCount))
                {
                    row[index] = (Half)(sample.X - 0.5f);
                    index++;
                    row[index] = (Half)(sample.Y - 0.5f);
                    index++;
                }
            }

            // TODO: could be an half float or unsigned byte instead of a float
            // TODO: two sample pair could be stored in one 4-channel value
            GL.TexImage1D(TextureTarget.Texture1D, 0, PixelInternalFormat.Rg16f,
                sampleCount, 0,
                PixelFormat.Rg, PixelType.HalfFloat, texturePtr);

            Marshal.FreeHGlobal(texturePtr);

            GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
        }
Beispiel #49
0
 private static Func<int, IEnumerable<Vector2d>> GetSemiJitteredSampler()
 {
     Sampler sampler = new Sampler();
     return (sampleCount) => sampler.GenerateSemiJitteredSamples(sampleCount, 0.5);
 }
Beispiel #50
0
        internal Tracer(TracerSettings settings, IAgentWriter agentWriter, ISampler sampler, IScopeManager scopeManager, IDogStatsd statsd)
        {
            // update the count of Tracer instances
            Interlocked.Increment(ref _liveTracerCount);

            Settings = settings ?? TracerSettings.FromDefaultSources();
            Settings.Freeze();

            // if not configured, try to determine an appropriate service name
            DefaultServiceName = Settings.ServiceName ??
                                 GetApplicationName() ??
                                 UnknownServiceName;

            // only set DogStatsdClient if tracer metrics are enabled
            if (Settings.TracerMetricsEnabled)
            {
                Statsd = statsd ?? CreateDogStatsdClient(Settings, DefaultServiceName, Settings.DogStatsdPort);
            }

            _agentWriter = agentWriter ?? new AgentWriter(new Api(Settings.AgentUri, TransportStrategy.Get(Settings), Statsd), Statsd, queueSize: Settings.TraceQueueSize);

            _scopeManager = scopeManager ?? new AsyncLocalScopeManager();
            Sampler       = sampler ?? new RuleBasedSampler(new RateLimiter(Settings.MaxTracesSubmittedPerSecond));

            if (!string.IsNullOrWhiteSpace(Settings.CustomSamplingRules))
            {
                foreach (var rule in CustomSamplingRule.BuildFromConfigurationString(Settings.CustomSamplingRules))
                {
                    Sampler.RegisterRule(rule);
                }
            }

            if (Settings.GlobalSamplingRate != null)
            {
                var globalRate = (float)Settings.GlobalSamplingRate;

                if (globalRate < 0f || globalRate > 1f)
                {
                    Log.Warning("{0} configuration of {1} is out of range", ConfigurationKeys.GlobalSamplingRate, Settings.GlobalSamplingRate);
                }
                else
                {
                    Sampler.RegisterRule(new GlobalSamplingRule(globalRate));
                }
            }

            // Register callbacks to make sure we flush the traces before exiting
            AppDomain.CurrentDomain.ProcessExit  += CurrentDomain_ProcessExit;
            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;

            try
            {
                // Registering for the AppDomain.UnhandledException event cannot be called by a security transparent method
                // This will only happen if the Tracer is not run full-trust
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Unable to register a callback to the AppDomain.UnhandledException event.");
            }

            try
            {
                // Registering for the cancel key press event requires the System.Security.Permissions.UIPermission
                Console.CancelKeyPress += Console_CancelKeyPress;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Unable to register a callback to the Console.CancelKeyPress event.");
            }

            // start the heartbeat loop
            _heartbeatTimer = new Timer(HeartbeatCallback, state: null, dueTime: TimeSpan.Zero, period: TimeSpan.FromMinutes(1));

            // If configured, add/remove the correlation identifiers into the
            // LibLog logging context when a scope is activated/closed
            if (Settings.LogsInjectionEnabled)
            {
                InitializeLibLogScopeEventSubscriber(_scopeManager, DefaultServiceName, Settings.ServiceVersion, Settings.Environment);
            }

            if (Interlocked.Exchange(ref _firstInitialization, 0) == 1)
            {
                if (Settings.StartupDiagnosticLogEnabled)
                {
                    _ = WriteDiagnosticLog();
                }

                if (Settings.RuntimeMetricsEnabled)
                {
                    _runtimeMetricsWriter = new RuntimeMetricsWriter(Statsd ?? CreateDogStatsdClient(Settings, DefaultServiceName, Settings.DogStatsdPort), TimeSpan.FromSeconds(10));
                }
            }
        }
Beispiel #51
0
 public static InfoBuffer GetSamplerInfo(Sampler sampler, SamplerInfo paramName, out ErrorCode error)
 {
     return GetInfo(GetSamplerInfo, sampler, paramName, out error);
 }
Beispiel #52
0
        private void GenerateLensSamplesTexture(int textureId, int tileSize, int sqrtSampleCount, int totalSampleCount, float lensApertureRadius)
        {
            GL.BindTexture(TextureTarget.Texture3D, textureId);
            // size of a group of samples for a single pixel
            int bands = 2;
            int groupSize = bands * totalSampleCount;
            int textureSize = groupSize * tileSize * tileSize;

            Sampler sampler = new Sampler();
            IntPtr texturePtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * textureSize);
            unsafe
            {
                int zStride = bands * tileSize * tileSize;
                for (int y = 0; y < tileSize; y++)
                {
                    for (int x = 0; x < tileSize; x++)
                    {
                        float* row = (float*)texturePtr + bands * (y * tileSize + x);
                        int index = 0;
                        // Z dimension, totalSampleCount times
                        foreach (Vector2d sample in
                            sampler.GenerateJitteredSamples(sqrtSampleCount))
                        {
                            Vector2d lensPos = lensApertureRadius *
                                //2 * (sample - new Vector2d(0.5, 0.5));
                            Sampler.ConcentricSampleDisk(sample);
                            row[index] = (float)lensPos.X;
                            row[index + 1] = (float)lensPos.Y;
                            index += zStride;
                        }
                    }
                }
            }

            // TODO: could be an unsigned byte instead of a float
            // TODO: two sample pair could be stored in one 4-channel value
            GL.TexImage3D(TextureTarget.Texture3D, 0, PixelInternalFormat.Rg32f,
                tileSize, tileSize, totalSampleCount, 0,
                PixelFormat.Rg, PixelType.Float, texturePtr);

            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapR, (int)TextureWrapMode.Clamp);
        }
Beispiel #53
0
        public Presenter(Context glContext)
        {
            this.glContext = glContext;
            glPipeline = glContext.Pipeline;

            sourceFramebuffer = new Framebuffer(glContext);
            destinationFramebuffer = new Framebuffer(glContext);

            vertices = new Buffer(glContext, BufferTarget.ArrayBuffer, 4 * 8 * sizeof(float), BufferUsageHint.StaticDraw, new Data(new[]
            {
                new Vertex(-1f, -1f),
                new Vertex(-1f, 1f),
                new Vertex(1f, 1f),
                new Vertex(1f, -1f)
            }));

            indices = new Buffer(glContext, BufferTarget.ElementArrayBuffer, 6 * sizeof(ushort), BufferUsageHint.StaticDraw, new Data(new ushort[]
            {
                0, 1, 2, 0, 2, 3
            }));

            sampler = new Sampler();
            sampler.SetMagFilter(TextureMagFilter.Nearest);
            sampler.SetMinFilter(TextureMinFilter.Nearest);

            string shaderErrors;
            if (!VertexShader.TryCompile(VertexShaderText, out vertexShader, out shaderErrors) ||
                !FragmentShader.TryCompile(FragmentShaderText, out fragmentShader, out shaderErrors) ||
                !ShaderProgram.TryLink(glContext, new ShaderProgramDescription
                    {
                        VertexShaders = vertexShader,
                        FragmentShaders = fragmentShader,
                        VertexAttributeNames = new[] { "in_position" },
                        SamplerNames = new[] { "Image" }
                    },
                    out program, out shaderErrors))
                throw new ArgumentException("Program errors:\n\n" + shaderErrors);

            vertexArray = new VertexArray(glContext);
            vertexArray.SetElementArrayBuffer(glContext, indices);
            vertexArray.SetVertexAttributeF(glContext, 0, vertices, VertexAttributeDimension.Two, VertexAttribPointerType.Float, false, 8, 0);
        }
Beispiel #54
0
 public void Begin(
     Sampler samplerState,
     in ColorRgbaF clearColor)
Beispiel #55
0
		internal MGFXShader (GraphicsDevice device, BinaryReader reader)
		{
			var isVertexShader = reader.ReadBoolean ();

#if OPENGL
			if (isVertexShader)
				ShaderType = ShaderType.VertexShader;
			else
				ShaderType = ShaderType.FragmentShader;
#endif // OPENGL

			var shaderLength = (int)reader.ReadUInt16 ();
			var shaderBytecode = reader.ReadBytes (shaderLength);

			var samplerCount = (int)reader.ReadByte ();
			_samplers = new Sampler[samplerCount];
			for (var s = 0; s < samplerCount; s++) {
				_samplers [s].type = (SamplerType)reader.ReadByte ();
				_samplers [s].index = reader.ReadByte ();
#if OPENGL
				_samplers [s].name = reader.ReadString ();
#endif
				_samplers [s].parameter = (int)reader.ReadByte ();
			}

			var cbufferCount = (int)reader.ReadByte ();
			_cbuffers = new int[cbufferCount];
			for (var c = 0; c < cbufferCount; c++)
				_cbuffers [c] = (int)reader.ReadByte ();

#if DIRECTX

			var d3dDevice = device._d3dDevice;
			if (isVertexShader)
			{
				_vertexShader = new VertexShader(d3dDevice, shaderBytecode, null);

				// We need the bytecode later for allocating the
				// input layout from the vertex declaration.
				Bytecode = shaderBytecode;
				
				HashKey = Effect.ComputeHash(Bytecode);
			}
			else
				_pixelShader = new PixelShader(d3dDevice, shaderBytecode);

#endif // DIRECTX

#if OPENGL
			var attributeCount = (int)reader.ReadByte ();
			_attributes = new Attribute[attributeCount];
			for (var a = 0; a < attributeCount; a++) {
				_attributes [a].name = reader.ReadString ();
				_attributes [a].usage = (VertexElementUsage)reader.ReadByte ();
				_attributes [a].index = reader.ReadByte ();
				_attributes [a].format = reader.ReadInt16 ();
			}

			_glslCode = System.Text.Encoding.ASCII.GetString (shaderBytecode);
			Compile ();
#endif // OPENGL
		}
 public void Render(Texture heightmap, Sampler heightmapSampler)
 {
     gb.Render(() =>
     {
         heightmapSampler.Bind(TextureUnit.Texture0);
     },
     (sp) =>
     {
         sp.SetUniform("heightmap", 0);
         sp.SetUniform("texsize", (float)heightmap.Width);
     });
 }
Beispiel #57
0
    //▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
    // Use this for initialization
    void Start()
    {
        oscA     = new OscRamp();
        flt      = new RCFilter();
        kickDrum = new Sampler(kickSample);
        vca      = new Envelope();

        flt.input = oscA.output; // TODO: connect method

        slidderCut.onValueChanged.AddListener((float v) => { flt.cut = v; });
        slidderRez.onValueChanged.AddListener((float v) => { flt.rez = v; });

        Tempo = 133f;

        freqTable = new FreqTable ();
        freqTable.Create ();
    }
Beispiel #58
0
        /// <summary>
        ///  Build a GroupBy Dictionary for Peek.
        /// </summary>
        /// <remarks>
        ///  Peek identifies each distinct common value and the approximate percentage of rows with it.
        ///  If we have many matching rows, we can sample - the sample will have any common values in it.
        ///  However, we don't know how many matches we have in advance.
        ///  Therefore, we build a Dictionary of all rows, 1/8 of rows, 1/64 of rows, and 1/512 of rows.
        ///  As soon as a given sample has enough samples to be statistically valid, we stop collecting the larger subsets.
        ///  This strategy allows us to run the overall query only once, end up with a large enough sample, and avoid building giant Dictionaries.
        /// </remarks>
        /// <param name="cancellationToken">CancellationToken to request early stop</param>
        private void BuildDictionary(CancellationToken cancellationToken)
        {
            // Short-circuit path if there's one key column and it's an EnumColumn
            if (_column.IsEnumColumn())
            {
                BuildSingleEnumColumnDictionary(cancellationToken);
                return;
            }

            // Build a Random instance to sample rows
            Random r = new Random();

            // Build a Dictionary and CountAggregator for each sample
            GroupByDictionary[] dictionaries = new GroupByDictionary[SampleCount];
            CountAggregator[]   counts       = new CountAggregator[SampleCount];
            int[][]             remapArrays  = new int[SampleCount][];
            for (int i = 0; i < SampleCount; ++i)
            {
                dictionaries[i] = new GroupByDictionary(new ColumnDetails[] { _column.ColumnDetails });
                counts[i]       = new CountAggregator();
            }

            // Retrieve the column getter
            Func <XArray> columnGetter = _column.CurrentGetter();

            // Track which sample we'll currently report
            int currentSample = 0;

            XArray[] arrays = new XArray[1];
            int      count;

            while ((count = _source.Next(XTableExtensions.DefaultBatchSize, cancellationToken)) != 0)
            {
                // Get the column values
                arrays[0] = columnGetter();

                // Build the GroupBy count for all rows and successive 1/8 samples
                for (int i = 0; i < SampleCount; ++i)
                {
                    // Add these to the Join Dictionary
                    if (i >= currentSample)
                    {
                        // Choose buckets for each row
                        XArray indicesForRows = dictionaries[i].FindOrAdd(arrays);

                        // Identify the bucket for each row and aggregate them
                        counts[i].Add(indicesForRows, dictionaries[i].Count);

                        // If this sample now has enough values, stop collecting bigger row sets
                        if (currentSample == i - 1 && counts[i].TotalRowCount > RequiredSampleSize)
                        {
                            // If every row was unique, stop early and don't set outputs (zero rows)
                            if (ShouldStopEarly(dictionaries[currentSample], counts[currentSample]))
                            {
                                return;
                            }

                            dictionaries[currentSample] = null;
                            counts[currentSample]       = null;
                            currentSample++;
                        }
                    }

                    // Each successive dictionary has ~1/8 of the rows of the previous one
                    if (i < SampleCount - 1)
                    {
                        ArraySelector sample = Sampler.Eighth(arrays[0].Selector, r, ref remapArrays[i]);
                        arrays[0] = arrays[0].Reselect(sample);
                    }
                }
            }

            // Once the loop is done, get the distinct values and aggregation results
            PostSortAndFilter(dictionaries[currentSample].DistinctKeys()[0], counts[currentSample].Values, counts[currentSample].TotalRowCount, currentSample == 0);
        }
Beispiel #59
0
		public static DXShaderData CreateGLSL (byte[] byteCode, List<DXConstantBufferData> cbuffers, int sharedIndex, Dictionary<string, SamplerStateInfo> samplerStates)
		{
			var dxshader = new DXShaderData ();
			dxshader.SharedIndex = sharedIndex;
			dxshader.Bytecode = (byte[])byteCode.Clone ();

			// Use MojoShader to convert the HLSL bytecode to GLSL.

			var parseDataPtr = MojoShader.NativeMethods.MOJOSHADER_parse (
				"glsl",
				byteCode,
				byteCode.Length,
				IntPtr.Zero,
				0,
				IntPtr.Zero,
				0,
				IntPtr.Zero,
				IntPtr.Zero,
				IntPtr.Zero);

			var parseData = DXHelper.Unmarshal<MojoShader.MOJOSHADER_parseData> (parseDataPtr);
			if (parseData.error_count > 0) {
				var errors = DXHelper.UnmarshalArray<MojoShader.MOJOSHADER_error> (
					parseData.errors,
					parseData.error_count
				);
				throw new Exception (errors [0].error);
			}

			switch (parseData.shader_type) {
			case MojoShader.MOJOSHADER_shaderType.MOJOSHADER_TYPE_PIXEL:
				dxshader.IsVertexShader = false;
				break;
			case MojoShader.MOJOSHADER_shaderType.MOJOSHADER_TYPE_VERTEX:
				dxshader.IsVertexShader = true;
				break;
			default:
				throw new NotSupportedException ();
			}
	

			// Conver the attributes.
			//
			// TODO: Could this be done using DX shader reflection?
			//
			{
				var attributes = DXHelper.UnmarshalArray<MojoShader.MOJOSHADER_attribute> (
						parseData.attributes, parseData.attribute_count);

				dxshader._attributes = new Attribute[attributes.Length];
				for (var i = 0; i < attributes.Length; i++) {
					dxshader._attributes [i].name = attributes [i].name;
					dxshader._attributes [i].index = attributes [i].index;
					dxshader._attributes [i].usage = DXEffectObject.ToXNAVertexElementUsage (attributes [i].usage);
				}
			}

			var symbols = DXHelper.UnmarshalArray<MojoShader.MOJOSHADER_symbol> (
					parseData.symbols, parseData.symbol_count);

			//try to put the symbols in the order they are eventually packed into the uniform arrays
			//this /should/ be done by pulling the info from mojoshader
			Array.Sort (symbols, delegate(MojoShader.MOJOSHADER_symbol a, MojoShader.MOJOSHADER_symbol b) {
				uint va = a.register_index;
				if (a.info.elements == 1)
					va += 1024; //hax. mojoshader puts array objects first
				uint vb = b.register_index;
				if (b.info.elements == 1)
					vb += 1024;
				return va.CompareTo (vb);
			}
			);//(a, b) => ((int)(a.info.elements > 1))a.register_index.CompareTo(b.register_index));

            // NOTE: It seems the latest versions of MojoShader only 
            // output vec4 register sets.  We leave the code below, but
            // the runtime has been optimized for this case.

			// For whatever reason the register indexing is 
			// incorrect from MojoShader.
			{
				uint bool_index = 0;
				uint float4_index = 0;
				uint int4_index = 0;

				for (var i = 0; i < symbols.Length; i++) {
					switch (symbols [i].register_set) {
					case MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_BOOL:
						symbols [i].register_index = bool_index;
						bool_index += symbols [i].register_count;
						break;

					case MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_FLOAT4:
						symbols [i].register_index = float4_index;
						float4_index += symbols[i].register_count;
						break;

					case MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_INT4:
						symbols [i].register_index = int4_index;
						int4_index += symbols [i].register_count;
						break;
					}
				}
			}

			// Get the samplers.
			var samplers = DXHelper.UnmarshalArray<MojoShader.MOJOSHADER_sampler> (
					parseData.samplers, parseData.sampler_count);
			dxshader._samplers = new Sampler[samplers.Length];
			for (var i = 0; i < samplers.Length; i++) 
            {
                // We need the original sampler name... look for that in the symbols.
                var originalSamplerName =
                    symbols.First(e => e.register_set == MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_SAMPLER &&
                    e.register_index == samplers[i].index
                ).name;

                var sampler = new Sampler
                {
                    //sampler mapping to parameter is unknown atm
                    parameter = -1,
                                      
                    // GLSL needs the MojoShader mangled sampler name.
                    samplerName = samplers[i].name,

                    // By default use the original sampler name for the parameter name.
                    parameterName = originalSamplerName,

                    textureSlot = samplers[i].index,
                    samplerSlot = samplers[i].index,
                    type = samplers[i].type,
                };

                SamplerStateInfo state;
                if (samplerStates.TryGetValue(originalSamplerName, out state))
                {
                    sampler.state = state.State;
                    sampler.parameterName = state.TextureName ?? originalSamplerName;
                }

                // Store the sampler.
			    dxshader._samplers[i] = sampler;
			}

			// Gather all the parameters used by this shader.
			var symbol_types = new [] { 
				new { name = dxshader.IsVertexShader ? "vs_uniforms_bool" : "ps_uniforms_bool", set = MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_BOOL, },
				new { name = dxshader.IsVertexShader ? "vs_uniforms_ivec4" : "ps_uniforms_ivec4", set = MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_INT4, },
				new { name = dxshader.IsVertexShader ? "vs_uniforms_vec4" : "ps_uniforms_vec4", set = MojoShader.MOJOSHADER_symbolRegisterSet.MOJOSHADER_SYMREGSET_FLOAT4, },
			};

			var cbuffer_index = new List<int> ();
			for (var i = 0; i < symbol_types.Length; i++) {
				var cbuffer = new DXConstantBufferData (symbol_types [i].name,
													   symbol_types [i].set,
													   symbols);
				if (cbuffer.Size == 0)
					continue;

				var match = cbuffers.FindIndex (e => e.SameAs (cbuffer));
				if (match == -1) {
					cbuffer_index.Add (cbuffers.Count);
					cbuffers.Add (cbuffer);
				} else
					cbuffer_index.Add (match);
			}
			dxshader._cbuffers = cbuffer_index.ToArray ();

			var glslCode = parseData.output;

#if GLSLOPTIMIZER
			//glslCode = GLSLOptimizer.Optimize(glslCode, ShaderType);
#endif

			// TODO: This sort of sucks... why does MojoShader not produce
			// code valid for GLES out of the box?

			// GLES platforms do not like this.
			glslCode = glslCode.Replace ("#version 110", "");

			// Add the required precision specifiers for GLES.

            var floatPrecision = dxshader.IsVertexShader ? "precision highp float;\r\n" : "precision mediump float;\r\n";

			glslCode = "#ifdef GL_ES\r\n" +
                 floatPrecision +
				"precision mediump int;\r\n" +
				"#endif\r\n" +
				glslCode;

			// Store the code for serialization.
			dxshader.ShaderCode = Encoding.ASCII.GetBytes (glslCode);

			return dxshader;
		}
Beispiel #60
0
        internal Tracer(TracerSettings settings, IAgentWriter agentWriter, ISampler sampler, IScopeManager scopeManager, IStatsd statsd)
        {
            // update the count of Tracer instances
            Interlocked.Increment(ref _liveTracerCount);

            Settings = settings ?? TracerSettings.FromDefaultSources();

            // if not configured, try to determine an appropriate service name
            DefaultServiceName = Settings.ServiceName ??
                                 GetApplicationName() ??
                                 UnknownServiceName;

            // only set DogStatsdClient if tracer metrics are enabled
            if (Settings.TracerMetricsEnabled)
            {
                // Run this first in case the port override is ready
                TracingProcessManager.SubscribeToDogStatsDPortOverride(
                    port =>
                {
                    Log.Debug("Attempting to override dogstatsd port with {0}", port);
                    Statsd = CreateDogStatsdClient(Settings, DefaultServiceName, port);
                });

                Statsd = statsd ?? CreateDogStatsdClient(Settings, DefaultServiceName, Settings.DogStatsdPort);
            }

            IApi apiClient = null;

            if (agentWriter == null)
            {
                if (Settings.ApiType.ToLower().Equals("zipkin"))
                {
                    apiClient = new ZipkinApi(Settings, delegatingHandler: null);
                }
            }

            _agentWriter  = agentWriter ?? new AgentWriter(apiClient, Statsd, Settings.SynchronousSend);
            _scopeManager = scopeManager ?? new AsyncLocalScopeManager();
            Sampler       = sampler ?? new RuleBasedSampler(new RateLimiter(Settings.MaxTracesSubmittedPerSecond));

            if (!string.IsNullOrWhiteSpace(Settings.CustomSamplingRules))
            {
                // User has opted in, ensure rate limiter is used
                RuleBasedSampler.OptInTracingWithoutLimits();

                foreach (var rule in CustomSamplingRule.BuildFromConfigurationString(Settings.CustomSamplingRules))
                {
                    Sampler.RegisterRule(rule);
                }
            }

            if (Settings.GlobalSamplingRate != null)
            {
                var globalRate = (float)Settings.GlobalSamplingRate;

                if (globalRate < 0f || globalRate > 1f)
                {
                    Log.Warning("{0} configuration of {1} is out of range", ConfigurationKeys.GlobalSamplingRate, Settings.GlobalSamplingRate);
                }
                else
                {
                    Sampler.RegisterRule(new GlobalSamplingRule(globalRate));
                }
            }

            // Register callbacks to make sure we flush the traces before exiting
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;
            AppDomain.CurrentDomain.DomainUnload       += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Console.CancelKeyPress += Console_CancelKeyPress;

            // start the heartbeat loop
            _heartbeatTimer = new Timer(HeartbeatCallback, state: null, dueTime: TimeSpan.Zero, period: TimeSpan.FromMinutes(1));

            // If configured, add/remove the correlation identifiers into the
            // LibLog logging context when a scope is activated/closed
            if (Settings.LogsInjectionEnabled)
            {
                InitializeLibLogScopeEventSubscriber(_scopeManager);
            }
        }