Exemple #1
1
        public static MapRepresentation Create(HttpRequestMessage req, IList<ContextSurface> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            OptionalProperty[] memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToArray();
            INakedObjectSurface target = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full) {
                var tempProperties = new List<OptionalProperty>();

                if (flags.SimpleDomainModel) {
                    var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName());
                    tempProperties.Add(dt);
                }

                if (flags.FormalDomainModel) {
                    var links = new OptionalProperty(JsonPropertyNames.Links, new[] {
                        Create(new OptionalProperty(JsonPropertyNames.Rel, RelValues.DescribedBy),
                               new OptionalProperty(JsonPropertyNames.Href, new UriMtHelper(req, target.Specification).GetDomainTypeUri()))
                    });
                    tempProperties.Add(links);
                }

                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else {
                mapRepresentation = Create(memberValues);
            }

            mapRepresentation.SetContentType(mt);

            return mapRepresentation;
        }
Exemple #2
1
        public static MapRepresentation Create(HttpRequestMessage req, ContextSurface context, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            var objectContextSurface = context as ObjectContextSurface;
            var actionResultContextSurface = context as ActionResultContextSurface;
            MapRepresentation mapRepresentation;


            if (objectContextSurface != null) {
                List<OptionalProperty> optionalProperties = objectContextSurface.VisibleProperties.Where(p => p.Reason != null || p.ProposedValue != null).Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToList();
                if (!string.IsNullOrEmpty(objectContextSurface.Reason)) {
                    optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, objectContextSurface.Reason));
                }
                mapRepresentation = Create(optionalProperties.ToArray());
            }
            else if (actionResultContextSurface != null) {
                List<OptionalProperty> optionalProperties = actionResultContextSurface.ActionContext.VisibleParameters.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToList();

                if (!string.IsNullOrEmpty(actionResultContextSurface.Reason)) {
                    optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, actionResultContextSurface.Reason));
                }
                mapRepresentation = Create(optionalProperties.ToArray());
            }
            else {
                mapRepresentation = GetMap(req, context, flags);
            }


            mapRepresentation.SetContentType(mt);


            return mapRepresentation;
        }
    void OnGUI()
    {
        GUILayout.BeginHorizontal();
            GUI.enabled = m_Format != Format.Pretty;
            if( GUILayout.Button ("PrettyFormat") )
            {
                m_Format = Format.Pretty;
            }

            GUI.enabled = m_Format != Format.Plain;
            if( GUILayout.Button ("Plain Format") )
            {
                m_Format = Format.Plain;
            }
        GUILayout.EndHorizontal();

        GUI.enabled = true;
        if( GUILayout.Button("Serialize", GUILayout.Height (100)) )
        {
            _TestSerialInfo();
        }

        m_ScrollPos = GUILayout.BeginScrollView(m_ScrollPos, GUILayout.Width (Screen.width-200));
        if( m_str1.Length > 0)
        {
            GUILayout.TextArea(m_str1);
        }
        GUILayout.EndScrollView();
    }
 public void Init(
     string name,
     int width,
     int height,
     Format resourceFormat,
     Format srvFormat,
     BindFlags bindFlags,
     int samplesCount,
     int samplesQuality,
     ResourceOptionFlags roFlags,
     ResourceUsage ru,
     int mipmapLevels,
     CpuAccessFlags cpuAccessFlags)
 {
     m_name = name;
     m_size = new Vector2I(width, height);
     m_resourceFormat = resourceFormat;
     m_srvFormat = srvFormat;
     m_bindFlags = bindFlags;
     m_samplesCount = samplesCount;
     m_samplesQuality = samplesQuality;
     m_roFlags = roFlags;
     m_resourceUsage = ru;
     m_mipmapLevels = mipmapLevels;
     m_cpuAccessFlags = cpuAccessFlags;
 }
Exemple #5
0
 public DataBuffer CreateIndexBuffer(int length, Usage usage, Format format, Pool pool)
 {
     IntPtr pOut = IntPtr.Zero;
     int res = Interop.Calli(comPointer, length, (int)usage, (int)format, (int)pool, (IntPtr)(void*)&pOut, IntPtr.Zero,(*(IntPtr**)comPointer)[27]);
     if( res < 0 ) { throw new SharpDXException( res ); }
     return new DataBuffer( pOut );
 }
		public void TestContainer(Format format, string expectedOutput)
		{
			var schema = new Scope();

			schema.Element<Item>()
				.Attributes()
				.Add(x => x.Name)
				.End()
				.Init();

			schema.Element<Container>()
				.Elements()
				.Add(x => x.Items)
				.End()
				.Init();

			var container = new Container(new[] {new Item("a"), new Item("b")});
			var output = schema.ToString(container, format);
			Assert.AreEqual(expectedOutput, output);
			
			var container2 = schema.Parse<Container>(output, format);
			Assert.AreEqual(container.Items.Count, container2.Items.Count);
			Assert.AreEqual(container.Items[0].Name, container2.Items[0].Name);
			Assert.AreEqual(container.Items[1].Name, container2.Items[1].Name);
		}
Exemple #7
0
        public D3D9DepthBuffer( PoolId poolId, D3DRenderSystem renderSystem,
            Device creator, Surface depthBufferSurf,
            Format fmt, int width, int height,
            MultisampleType fsaa, int multiSampleQuality,
            bool isManual) :
            base(poolId, 0, width, height, (int)fsaa, "", isManual)
        {
            depthBuffer = depthBufferSurf;
            this.creator = creator;
            this.multiSampleQuality = multiSampleQuality;
            d3dFormat = fmt;
            this.renderSystem = renderSystem;

            switch (fmt)
            {
                case Format.D16Lockable:
                case Format.D15S1:
                case Format.D16:
                    bitDepth = 16;
                    break;
                case Format.D32:
                case Format.D24S8:
                case Format.D24X8:
                case Format.D24X4S4:
                case Format.D32Lockable:
                case Format.D24SingleS8:
                    bitDepth = 32;
                    break;
            }
        }
Exemple #8
0
 public static byte[] Decompress(int width, int height, byte[] source, Format format)
 {
     using (var strm = new MemoryStream(source))
     {
         return Decompress(width, height, new BinaryReader(strm), format);
     }
 }
Exemple #9
0
        public Consumer(string host, string groupName, string instanceId, Format format, string offset = "smallest")
        {
            this.host = host;
            this.groupName = groupName;
            this.instanceId = instanceId;
            this.format = format;

            var contentType = "application/vnd.kafka.v1+json";
            var data = new Dictionary<string, string>
            {
                {"name", instanceId},
                {"format", format.ToString().ToLower()},
                {"auto.offset.reset", offset}
            };
            try
            {
                var responseString = WebRequestHelper.Post(host, $"consumers/{groupName}", JsonConvert.SerializeObject(data),
                    contentType);
                dynamic response = JsonConvert.DeserializeObject<dynamic>(responseString);
                this.instanceId = response.instance_id.ToObject<string>();
                baseUri = response.base_uri.ToObject<string>();
            }
            catch (Exception e)
            {
                // it means, that consumer with this name already exists
                log.Warn(e.Message);
                baseUri = $"{host}/consumers/{groupName}/instances/{instanceId}";
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="VertexElement" /> struct.
 /// </summary>
 /// <param name="semanticName">Name of the semantic.</param>
 /// <param name="semanticIndex">Index of the semantic.</param>
 /// <param name="format">The format.</param>
 /// <param name="alignedByteOffset">The aligned byte offset.</param>
 public VertexElementAttribute(string semanticName, int semanticIndex, Format format, int alignedByteOffset = VertexElement.AppendAligned)
 {
     this.semanticName = semanticName;
     this.semanticIndex = semanticIndex;
     this.format = format;
     this.alignedByteOffset = alignedByteOffset;
 }
Exemple #11
0
        public static string GetContentType(Format formats)
        {
            switch (formats)
            {
                case Format.Soap11:
                case Format.Soap12:
                case Format.Xml:
                    return Xml;

                case Format.Json:
                    return Json;

                case Format.Jsv:
                    return JsvText;

                case Format.Csv:
                    return Csv;

                case Format.ProtoBuf:
                    return ProtoBuf;

                case Format.MsgPack:
                    return MsgPack;

                default:
                    return null;
            }
        }
		public FormattingInfo(FormattingInfo parent, FormatDetails formatDetails, Format format, object currentValue)
		{
			this.Parent = parent;
			CurrentValue = currentValue;
			Format = format;
			FormatDetails = formatDetails;
		}
Exemple #13
0
        public ShaderResourceView ToTexture3D(Device graphicsDevice, Format format)
        {
            int sizeInBytes = sizeof(float) * width * height * depth;

            DataStream stream = new DataStream(sizeInBytes, true, true);
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    for (int z = 0; z < depth; z++)
                        stream.Write(values[x, y, z]);
            stream.Position = 0;

            DataBox dataBox = new DataBox(sizeof(float) * width, sizeof(float) * width * height, stream);
            Texture3DDescription description = new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Depth = depth,
                Format = format,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = width
            };
            Texture3D texture = new Texture3D(graphicsDevice, description, dataBox);

            stream.Dispose();

            return new ShaderResourceView(graphicsDevice, texture);
        }
Exemple #14
0
        public Config(Writer writer, Format fmt, GetConfig get_new_config)
        {
            m_fmt = fmt;

            m_get_new_config = get_new_config ?? no_new_config;

            file = new VectFormatter(writer);
            file.seperator          = fmt.line_spacing > 0 ? "" : " ";
            file.seperator_spacing  = fmt.line_spacing;
            file.footer_spacing     = 1;

            top_vect = new_vect(writer, fmt.format_vect, "#(", "TV");
            vect     = new_vect(writer, fmt.format_vect, "#(", "V");
            vect_cdr = new_vect(writer, fmt.format_vect, " . #(", "-V");

            cons      = new_cons(writer, fmt.do_abbrev, true, "C");
            top_cons  = new_cons(writer, fmt.do_abbrev, true, "TC");
            vect_cons = new_cons(writer, fmt.do_abbrev, fmt.format_vect, "VC");
            head_cons = new_cons(writer, fmt.do_abbrev, fmt.format_head, "HC");

            vect_cons_cdr = new_cons_cdr(writer, fmt.format_vect, fmt.dot_cdr, fmt.dot_nil, "-VC");
            head_cons_cdr = new_cons_cdr(writer, fmt.format_head, fmt.dot_cdr, fmt.dot_nil, "-HC");
            appl_cons_cdr = new_cons_cdr(writer, fmt.format_appl, fmt.dot_cdr, fmt.dot_nil, "-AC");
            data_cons_cdr = new_cons_cdr(writer, fmt.format_data, fmt.dot_cdr, fmt.dot_nil, "-DC");

            atom = new AtomFormatter(writer);

            atom_cdr = new AtomFormatter(writer);
            atom_cdr.header = " . ";
        }
 public DisplayMode EnumAdapterModes(int adapter, Format format, int mode)
 {
     DisplayMode modeRef = new DisplayMode();
     int res = Interop.Calli(comPointer, adapter, (int)format, mode, (IntPtr)(void*)&modeRef,(*(IntPtr**)comPointer)[7]);
     if( res < 0 ) { throw new SharpDXException( res ); }
     return modeRef;
 }
Exemple #16
0
        public BlurComponent(Device graphics, int size)
        {
            _graphics = graphics;

            Dims = size;
            Format = Format.A8R8G8B8;

            _sampleOffsetsHoriz = new Vector4D[SampleCount];
            _sampleOffsetsVert = new Vector4D[SampleCount];

            _sampleWeightsHoriz = new float[SampleCount];
            _sampleWeightsVert = new float[SampleCount];

            int width = Dims - 5;
            int height = Dims - 5;

            SetBlurEffectParameters(1.0f / width, 0, ref _sampleOffsetsHoriz, ref _sampleWeightsHoriz);
            SetBlurEffectParameters(0, 1.0f / height, ref _sampleOffsetsVert, ref _sampleWeightsVert);

            _effect = new GaussianBlurEffect(_graphics);

            OutputTexture = new Texture(_graphics, Dims, Dims, 1, Usage.RenderTarget, Format, Pool.Default);
            _intermediateTexture = new Texture(_graphics, Dims, Dims, 1, Usage.RenderTarget, Format, Pool.Default);

            _sprite = new Sprite(_graphics);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////
        /// Static and helper functions
        ////////////////////////////////////////////////////////////////////////////////////////////////
        public static bool Import(tk2dTileMap tileMap, Format format)
        {
            var importer = new Importer();

            string ext = "";
            switch (format)
            {
                case Format.TMX:
                    if (!importer.CheckZlib()) return false;
                    ext = "tmx";
                break;
            }

            string path = EditorUtility.OpenFilePanel("Import tilemap", "", ext);
            if (path.Length == 0)
                return false;

            string message = "";
            switch (format)
            {
            case Format.TMX: message = importer.ImportTMX(path); break;
            }

            if (message.Length != 0)
            {
                EditorUtility.DisplayDialog("Tilemap failed to import", message, "Ok");
                return false;
            }

            importer.PopulateTilemap(tileMap);
            return true;
        }
Exemple #18
0
        /// <summary>
        /// Creates a new graphics resource.
        /// </summary>
        /// <param name="device">The graphics device to use.</param>
        /// <param name="dimensions">The resource dimensions.</param>
        /// <param name="format">The resource's DXGI format.</param>
        /// <param name="renderTargetView">Whether to bind as RTV.</param>
        /// <param name="shaderResourceView">Whether to bind as SRV.</param>
        /// <param name="hasMipMaps">Whether to enable mip-maps for this texture.</param>
        public GraphicsResource(Device device, Size dimensions, Format format, Boolean renderTargetView = true, Boolean shaderResourceView = true, Boolean hasMipMaps = false)
        {
            if ((!renderTargetView) && (!shaderResourceView))
                throw new ArgumentException("The requested resource cannot be bound at all to the pipeline.");

            if ((hasMipMaps) && ((!renderTargetView) || (!shaderResourceView)))
                throw new ArgumentException("A resource with mipmaps must be bound as both input and output.");

            BindFlags bindFlags = (renderTargetView ? BindFlags.RenderTarget : 0) | (shaderResourceView ? BindFlags.ShaderResource : 0);
            ResourceOptionFlags optionFlags = (hasMipMaps ? ResourceOptionFlags.GenerateMipMaps : 0);
            int mipLevels = (hasMipMaps ? MipLevels(dimensions) : 1);

            Resource = new Texture2D(device, new Texture2DDescription()
            {
                Format = format,
                BindFlags = bindFlags,
                Width = dimensions.Width,
                Height = dimensions.Height,

                ArraySize = 1,
                MipLevels = mipLevels,
                OptionFlags = optionFlags,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            });

            RTV = (  renderTargetView ?   new RenderTargetView(device, Resource) : null);
            SRV = (shaderResourceView ? new ShaderResourceView(device, Resource) : null);
        }
Exemple #19
0
 /// <summary>Initializes a new instance of the <see cref="DisplayMode"/> class.</summary>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="refreshRate">The refresh rate.</param>
 public DisplayMode(Format pixelFormat, int width, int height, Rational refreshRate)
 {
     this.pixelFormat = pixelFormat;
     this.width = width;
     this.height = height;
     this.refreshRate = refreshRate;
 }
		public SqlUserDefinedTypeAttribute (Format f)
		{
			Format = f;
			IsByteOrdered = false;
			IsFixedLength = false;
			MaxByteSize = MaxByteSizeValue;
		}
    public Statistic(string name, float value, Format f)
    {
        this.name = name;
        Debug.Log("Real KDR: " + value);

        switch(f){
            case (Format.percentage) :
            {
                this.value = RoundFloat(value,2).ToString();
                this.value = value*100 + "%";
                break;
            }
            case (Format.ratio):
            {
                this.value = RoundFloat(value,2).ToString();
                break;
            }
            case (Format.time) :
            {
                this.value =  string.Format("{0}:{01:00}", (int)value / 60, (int)value % 60);
                break;
            }
            case (Format.none) :
            {
                this.value = value.ToString();
                break;
            }
        }
    }
        internal void Clear()
        {
            m_deviceContext.ClearState();

            m_inputLayout = null;
            m_primitiveTopology = PrimitiveTopology.Undefined;
            m_indexBufferRef = null;
            m_indexBufferFormat = Format.Unknown;
            m_indexBufferOffset = 0;
            for (int i = 0; i < m_vertexBuffers.Length; i++)
                m_vertexBuffers[i] = null;
            for (int i = 0; i < m_vertexBuffersStrides.Length; i++)
                m_vertexBuffersStrides[i] = 0;

            m_blendState = null;
            m_stencilRef = 0;
            m_depthStencilState = null;
            m_rtvsCount = 0;
            for (int i = 0; i < m_rtvs.Length; i++)
                m_rtvs[i] = null;
            m_dsv = null;

            m_rasterizerState = null;
            m_scissorLeftTop = new Vector2I(-1, -1);
            m_scissorRightBottom = new Vector2I(-1, -1);
            m_viewport = default(RawViewportF);

            m_targetBuffer = null;
            m_targetOffsets = 0;

            m_statistics.ClearStates++;
        }
Exemple #23
0
 /// <summary>
 /// Inflate the data with the given format stored in a buffer
 /// </summary>
 /// <param name="buffer">A view with the encoded data</param>
 /// <param name="format">An inflated format object</param>
 /// <returns>Return null, an ArrayList or a single value (ulong, long, float, Token or string)</returns>
 internal static object Inflate(BufferView buffer, Format format)
 {
     ArrayList data = new ArrayList();
     if (InflateData.ReadElement(buffer, data, format.Root).Length != 0)
         throw new ArgumentException("Unable to read data in the given format");
     return data.Count == 0 ? null : (data.Count == 1 ? data[0] : data);
 }
Exemple #24
0
 /// <summary>
 /// Gets the number of alpha channel bits.
 /// </summary>
 public static int GetAlphaChannelBits(Format format)
 {
   switch (format)
   {
     case Format.R8G8B8:
       return 0;
     case Format.A8R8G8B8:
       return 8;
     case Format.X8R8G8B8:
       return 0;
     case Format.R5G6B5:
       return 0;
     case Format.X1R5G5B5:
       return 0;
     case Format.A1R5G5B5:
       return 1;
     case Format.A4R4G4B4:
       return 4;
     case Format.R3G3B2:
       return 0;
     case Format.A8R3G3B2:
       return 8;
     case Format.X4R4G4B4:
       return 0;
     case Format.A2B10G10R10:
       return 2;
     case Format.A2R10G10B10:
       return 2;
     default:
       return 0;
   }
 }
		public ImageSurface (Format format, int width, int height)
		{
			surface = NativeMethods.cairo_image_surface_create (format, width, height);
			lock (surfaces.SyncRoot){
				surfaces [surface] = this;
			}
		}
        public void EvaluateFormat(object current, Format format, ref bool handled, IOutput output, FormatDetails formatDetails)
        {
            if (format != null && format.HasNested) return;
            var formatText = format != null ? format.Text : "";
            TimeSpan fromTime;
            if (current is TimeSpan)
            {
                fromTime = (TimeSpan)current;
            }
            else if (current is DateTime && formatText.StartsWith("timestring"))
            {
                formatText = formatText.Substring(10);
                fromTime = DateTime.Now.Subtract((DateTime)current);
            }
            else
            {
                return;
            }
            var timeTextInfo = GetTimeTextInfo(formatDetails.Provider);
            if (timeTextInfo == null)
            {
                return;
            }
            var formattingOptions = TimeSpanFormatOptionsConverter.Parse(formatText);
            var timeString = TimeSpanUtility.ToTimeString(fromTime, formattingOptions, timeTextInfo);
            output.Write(timeString, formatDetails);
            handled = true;

        }
		public void SetIndexBuffer(Buffer indexBuffer, Format format, int offset)
		{
            DiagnosticUtilities.RaiseEvent(this, SettingIndexBuffer, DiagnosticUtilities.GetID(indexBuffer), format, offset);
			if (format != Format.R16_UInt && format != Format.R32_UInt)
				throw new ArgumentOutOfRangeException("format");
			_indexBufferBinding = new IndexBufferBinding(indexBuffer, format, offset);
		}
Exemple #28
0
        //-------------------------------------------------------------------
        // Constructor
        //-------------------------------------------------------------------
        public DrawDevice()
        {
            m_hwnd = IntPtr.Zero;
            m_pDevice = null;
            m_pSwapChain = null;

            m_d3dpp = null;
            m_Data = IntPtr.Zero;

            m_format = Format.X8R8G8B8;
            m_width = 0;
            m_height = 0;
            m_lDefaultStride = 0;
            m_PixelAR.Denominator = m_PixelAR.Numerator = 1;
            m_rcDest = Rectangle.Empty;

            VideoFormatDefs = new VideoFormatGUID[] {
                new VideoFormatGUID(MFMediaType.RGB32, TransformImage_RGB32, ARGB32_To_RGB32),
                new VideoFormatGUID(MFMediaType.RGB24, TransformImage_RGB24, ARGB32_To_RGB24),
                new VideoFormatGUID(MFMediaType.YUY2, TransformImage_YUY2, ARGB32_To_YUY2),
                new VideoFormatGUID(MFMediaType.NV12, TransformImage_NV12, ARGB32_To_NV12)
            };

            m_convertFn = null;
            m_bmpconvertFn = null;
        }
Exemple #29
0
        public D3DDevice(IntPtr windowPtr, bool bWindowed, long Width, long Height)
        {
            m_bWindowed = bWindowed;
            m_Format = Find16BitMode();

            PresentParameters presentParameters		 = new PresentParameters();
            presentParameters.Windowed				 = m_bWindowed;
            presentParameters.SwapEffect			 = SwapEffect.Discard;
            presentParameters.BackBufferCount		 = 1;
            presentParameters.PresentationInterval	 = PresentInterval.Immediate;
            presentParameters.AutoDepthStencilFormat = DepthFormat.D16;
            presentParameters.EnableAutoDepthStencil = true;

            if(!bWindowed)
            {
                presentParameters.BackBufferFormat	= m_Format;
                presentParameters.BackBufferWidth	= (int)Width;
                presentParameters.BackBufferHeight	= (int)Height;
            }
            else
            {
                presentParameters.BackBufferFormat	= Format.Unknown;
                presentParameters.BackBufferWidth	= (int)Width;
                presentParameters.BackBufferHeight	= (int)Height;
            }

            m_D3DDevice = new Microsoft.DirectX.Direct3D.Device(0,
                DeviceType.Hardware, windowPtr,
                CreateFlags.SoftwareVertexProcessing, presentParameters);
        }
Exemple #30
0
 public static int CompressedImageSize(Format format, int width, int height, int depth, int byteAlignment)
 {
     int rowPitch, slicePitch, totalSize;
     switch (format)
     {
         case Format.CompressedRgbaS3tcDxt1Ext:
         case Format.CompressedSrgbAlphaS3tcDxt1Ext:
         case Format.CompressedRedRgtc1: // bc4
         case Format.CompressedSignedRedRgtc1:
             TextureHelper.GetInfoForSetDataCompressed(4, width, height, depth, byteAlignment, out rowPitch, out slicePitch, out totalSize);
             return totalSize;
         case Format.CompressedRgbaS3tcDxt3Ext:
         case Format.CompressedSrgbAlphaS3tcDxt3Ext:
         case Format.CompressedRgbaS3tcDxt5Ext:
         case Format.CompressedSrgbAlphaS3tcDxt5Ext:
         case Format.CompressedRgRgtc2:
         case Format.CompressedSignedRgRgtc2:
         case Format.CompressedRgbaBptcUf:
         case Format.CompressedRgbaBptcSf:
         case Format.CompressedRgbaBptc:
         case Format.CompressedSrgbAlphaBptc:
             TextureHelper.GetInfoForSetDataCompressed(8, width, height, depth, byteAlignment, out rowPitch, out slicePitch, out totalSize);
             return totalSize;
         default:
             throw new InvalidOperationException(string.Format("Format '{0}' is not a known compressed format", format));
     }
 }
Exemple #31
0
        static IEnumerable <Color> GetColorsFromTexture(byte[] tex, Format format)
        {
            using (var br = new BinaryReaderX(new MemoryStream(tex)))
            {
                var etc1decoder = new Etc1.Decoder();

                while (true)
                {
                    int a = 255, r = 255, g = 255, b = 255;
                    switch (format)
                    {
                    case Format.L8:
                        b = g = r = br.ReadByte();
                        break;

                    case Format.A8:
                        a = br.ReadByte();
                        break;

                    case Format.LA44:
                        a = br.ReadNibble() * 17;
                        b = g = r = br.ReadNibble() * 17;
                        break;

                    case Format.LA88:
                        a = br.ReadByte();
                        b = g = r = br.ReadByte();
                        break;

                    case Format.HL88:
                        g = br.ReadByte();
                        r = br.ReadByte();
                        break;

                    case Format.RGB565:
                        var s = br.ReadUInt16();
                        b = (s % 32) * 33 / 4;
                        g = (s >> 5) % 64 * 65 / 16;
                        r = (s >> 11) * 33 / 4;
                        break;

                    case Format.RGB888:
                        b = br.ReadByte();
                        g = br.ReadByte();
                        r = br.ReadByte();
                        break;

                    case Format.RGBA5551:
                        var s2 = br.ReadUInt16();
                        a = (s2 & 1) * 255;
                        b = (s2 >> 1) % 32 * 33 / 4;
                        g = (s2 >> 6) % 32 * 33 / 4;
                        r = (s2 >> 11) % 32 * 33 / 4;
                        break;

                    case Format.RGBA4444:
                        a = br.ReadNibble() * 17;
                        b = br.ReadNibble() * 17;
                        g = br.ReadNibble() * 17;
                        r = br.ReadNibble() * 17;
                        break;

                    case Format.RGBA8888:
                        a = br.ReadByte();
                        b = br.ReadByte();
                        g = br.ReadByte();
                        r = br.ReadByte();
                        break;

                    case Format.ETC1:
                    case Format.ETC1A4:
                        yield return(etc1decoder.Get(() =>
                        {
                            var alpha = (format == Format.ETC1A4) ? br.ReadUInt64() : ulong.MaxValue;
                            return new Etc1.PixelData {
                                Alpha = alpha, Block = br.ReadStruct <Etc1.Block>()
                            };
                        }));

                        continue;

                    case Format.L4:
                        b = g = r = br.ReadNibble() * 17;
                        break;

                    case Format.A4:
                        a = br.ReadNibble() * 17;
                        break;

                    default:
                        throw new NotSupportedException($"Unknown image format {format}");
                    }
                    yield return(Color.FromArgb(a, r, g, b));
                }
            }
        }
Exemple #32
0
            public async Task RemindInternal(ulong targetId, bool isPrivate, string timeStr, [Remainder] string message)
            {
                var m = _regex.Match(timeStr);

                if (m.Length == 0)
                {
                    await ReplyErrorLocalized("remind_invalid_format").ConfigureAwait(false);

                    return;
                }

                string output         = "";
                var    namesAndValues = new Dictionary <string, int>();

                foreach (var groupName in _regex.GetGroupNames())
                {
                    if (groupName == "0")
                    {
                        continue;
                    }
                    int value;
                    int.TryParse(m.Groups[groupName].Value, out value);

                    if (string.IsNullOrEmpty(m.Groups[groupName].Value))
                    {
                        namesAndValues[groupName] = 0;
                        continue;
                    }
                    if (value < 1 ||
                        (groupName == "months" && value > 1) ||
                        (groupName == "weeks" && value > 4) ||
                        (groupName == "days" && value >= 7) ||
                        (groupName == "hours" && value > 23) ||
                        (groupName == "minutes" && value > 59))
                    {
                        await Context.Channel.SendErrorAsync($"Invalid {groupName} value.").ConfigureAwait(false);

                        return;
                    }
                    namesAndValues[groupName] = value;
                    output += m.Groups[groupName].Value + " " + groupName + " ";
                }
                var time = DateTime.Now + new TimeSpan(30 * namesAndValues["months"] +
                                                       7 * namesAndValues["weeks"] +
                                                       namesAndValues["days"],
                                                       namesAndValues["hours"],
                                                       namesAndValues["minutes"],
                                                       0);

                var rem = new Reminder
                {
                    ChannelId = targetId,
                    IsPrivate = isPrivate,
                    When      = time,
                    Message   = message,
                    UserId    = Context.User.Id,
                    ServerId  = Context.Guild.Id
                };

                using (var uow = DbHandler.UnitOfWork())
                {
                    uow.Reminders.Add(rem);
                    await uow.CompleteAsync();
                }

                try
                {
                    await Context.Channel.SendConfirmAsync(
                        "⏰ " + GetText("remind",
                                       Format.Bold(!isPrivate ? $"<#{targetId}>" : Context.User.Username),
                                       Format.Bold(message.SanitizeMentions()),
                                       Format.Bold(output),
                                       time, time)).ConfigureAwait(false);
                }
                catch
                {
                    // ignored
                }
                await StartReminder(rem, cancelAllToken);
            }
Exemple #33
0
        public async Task Google([Remainder] string terms = null)
        {
            terms = terms?.Trim();
            if (string.IsNullOrWhiteSpace(terms))
            {
                return;
            }

            terms = WebUtility.UrlEncode(terms).Replace(' ', '+');

            var fullQueryLink = $"https://www.google.ca/search?q={ terms }&gws_rd=cr,ssl&cr=countryUS";
            var config        = Configuration.Default.WithDefaultLoader();

            using (var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink))
            {
                var elems = document.QuerySelectorAll("div.g");

                var resultsElem  = document.QuerySelectorAll("#resultStats").FirstOrDefault();
                var totalResults = resultsElem?.TextContent;
                //var time = resultsElem.Children.FirstOrDefault()?.TextContent
                //^ this doesn't work for some reason, <nobr> is completely missing in parsed collection
                if (!elems.Any())
                {
                    return;
                }

                var results = elems.Select <IElement, GoogleSearchResult?>(elem =>
                {
                    var aTag = (elem.Children.FirstOrDefault()?.Children.FirstOrDefault() as IHtmlAnchorElement); // <h3> -> <a>
                    var href = aTag?.Href;
                    var name = aTag?.TextContent;
                    if (href == null || name == null)
                    {
                        return(null);
                    }

                    var txt = elem.QuerySelectorAll(".st").FirstOrDefault()?.TextContent;

                    if (txt == null)
                    {
                        return(null);
                    }

                    return(new GoogleSearchResult(name, href, txt));
                }).Where(x => x != null).Take(5);

                var embed = new EmbedBuilder()
                            .WithOkColor()
                            .WithAuthor(eab => eab.WithName(GetText("search_for") + " " + terms.TrimTo(50))
                                        .WithUrl(fullQueryLink)
                                        .WithIconUrl("http://i.imgur.com/G46fm8J.png"))
                            .WithTitle(Context.User.ToString())
                            .WithFooter(efb => efb.WithText(totalResults));

                var desc = await Task.WhenAll(results.Select(async res =>
                                                             $"[{Format.Bold(res?.Title)}]({(await _google.ShortenUrl(res?.Link))})\n{res?.Text?.TrimTo(400 - res.Value.Title.Length - res.Value.Link.Length)}\n\n"))
                           .ConfigureAwait(false);

                var descStr = string.Concat(desc);
                _log.Info(descStr.Length);
                await Context.Channel.EmbedAsync(embed.WithDescription(descStr)).ConfigureAwait(false);
            }
        }
 public static uint GetD3DFormat(this Format f)
 {
     return(kXenonFormats[(int)f]);
 }
Exemple #35
0
        public async Task Time([Remainder] string arg)
        {
            if (string.IsNullOrWhiteSpace(arg) || string.IsNullOrWhiteSpace(_creds.GoogleApiKey))
            {
                return;
            }

            var res = await _service.Http.GetStringAsync($"https://maps.googleapis.com/maps/api/geocode/json?address={arg}&key={_creds.GoogleApiKey}").ConfigureAwait(false);

            var obj = JsonConvert.DeserializeObject <GeolocationResult>(res);

            var currentSeconds = DateTime.UtcNow.UnixTimestamp();
            var timeRes        = await _service.Http.GetStringAsync($"https://maps.googleapis.com/maps/api/timezone/json?location={obj.results[0].Geometry.Location.Lat},{obj.results[0].Geometry.Location.Lng}&timestamp={currentSeconds}&key={_creds.GoogleApiKey}").ConfigureAwait(false);

            var timeObj = JsonConvert.DeserializeObject <TimeZoneResult>(timeRes);

            var time = DateTime.UtcNow.AddSeconds(timeObj.DstOffset + timeObj.RawOffset);

            await ReplyConfirmLocalized("time", Format.Bold(obj.results[0].FormattedAddress), Format.Code(time.ToString("HH:mm")), timeObj.TimeZoneName).ConfigureAwait(false);
        }
        /// <summary>
        /// Ensures that the image bindings are visible to the host GPU.
        /// Note: this actually performs the binding using the host graphics API.
        /// </summary>
        /// <param name="pool">The current texture pool</param>
        /// <param name="stage">The shader stage using the textures to be bound</param>
        /// <param name="stageIndex">The stage number of the specified shader stage</param>
        private void CommitImageBindings(TexturePool pool, ShaderStage stage, int stageIndex)
        {
            if (_imageBindings[stageIndex] == null)
            {
                return;
            }

            // Scales for images appear after the texture ones.
            int baseScaleIndex = _textureBindings[stageIndex]?.Length ?? 0;

            for (int index = 0; index < _imageBindings[stageIndex].Length; index++)
            {
                TextureBindingInfo bindingInfo = _imageBindings[stageIndex][index];

                int textureBufferIndex = bindingInfo.CbufSlot < 0 ? _textureBufferIndex : bindingInfo.CbufSlot;

                int packedId  = ReadPackedId(stageIndex, bindingInfo.Handle, textureBufferIndex);
                int textureId = UnpackTextureId(packedId);

                Texture texture = pool.Get(textureId);

                ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);

                bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);

                if (hostTexture != null && texture.Target == Target.TextureBuffer)
                {
                    // Ensure that the buffer texture is using the correct buffer as storage.
                    // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
                    // to ensure we're not using a old buffer that was already deleted.

                    Format format = bindingInfo.Format;

                    if (format == 0 && texture != null)
                    {
                        format = texture.Format;
                    }

                    _context.Methods.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, format, true);
                }
                else if (isStore)
                {
                    texture?.SignalModified();
                }

                if (_imageState[stageIndex][index].Texture != hostTexture || _rebind)
                {
                    if (UpdateScale(texture, bindingInfo, baseScaleIndex + index, stage))
                    {
                        hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
                    }

                    _imageState[stageIndex][index].Texture = hostTexture;

                    Format format = bindingInfo.Format;

                    if (format == 0 && texture != null)
                    {
                        format = texture.Format;
                    }

                    _context.Renderer.Pipeline.SetImage(bindingInfo.Binding, hostTexture, format);
                }
            }
        }