Exemple #1
0
        public StringBuilder zText; // The string collected so far

        #endregion Fields

        #region Constructors

        public StrAccum(int n)
        {
            db = null;
            zText = new StringBuilder(n);
            mxAlloc = 0;
            Context = null;
        }
Exemple #2
0
		} // TODO -- Convert to inline for speed

		/*
		** If pMem is an object with a valid string representation, this routine
		** ensures the internal encoding for the string representation is
		** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
		**
		** If pMem is not a string object, or the encoding of the string
		** representation is already stored using the requested encoding, then this
		** routine is a no-op.
		**
		** SQLITE_OK is returned if the conversion is successful (or not required).
		** SQLITE_NOMEM may be returned if a malloc() fails during conversion
		** between formats.
		*/

		private static int sqlite3VdbeChangeEncoding(Mem pMem, int desiredEnc)
		{
			int rc;
			Debug.Assert((pMem.flags & MEM_RowSet) == 0);
			Debug.Assert(desiredEnc == SQLITE_UTF8 || desiredEnc == SQLITE_UTF16LE
			|| desiredEnc == SQLITE_UTF16BE);
			if ((pMem.flags & MEM_Str) == 0 || pMem.enc == desiredEnc)
			{
				if (String.IsNullOrEmpty(pMem.z) && pMem.zBLOB != null)
					pMem.z = Encoding.UTF8.GetString(pMem.zBLOB, 0, pMem.zBLOB.Length);
				return SQLITE_OK;
			}
			Debug.Assert(pMem.db == null || sqlite3_mutex_held(pMem.db.mutex));
#if  SQLITE_OMIT_UTF16
			return SQLITE_ERROR;
#else

/* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
** then the encoding of the value may not have changed.
*/
rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
Debug.Assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
Debug.Assert(rc==SQLITE_OK    || pMem.enc!=desiredEnc);
Debug.Assert(rc==SQLITE_NOMEM || pMem.enc==desiredEnc);
return rc;
#endif
		}
Exemple #3
0
        //: static void Deephemeralize(Mem P) { }

        #endregion

        #region Name2

        public static void MemStoreType(Mem mem)
        {
            MEM flags = mem.Flags;
            if ((flags & MEM.Null) != 0) { mem.Type = TYPE.NULL; mem.Z = null; }
            else if ((flags & MEM.Int) != 0) mem.Type = TYPE.INTEGER;
            else if ((flags & MEM.Real) != 0) mem.Type = TYPE.FLOAT;
            else if ((flags & MEM.Str) != 0) mem.Type = TYPE.TEXT;
            else mem.Type = TYPE.BLOB;
        }
Exemple #4
0
        public void SetValue(Mem buffer)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            unsafe
            {
                IntPtr handle = buffer.Handle.DangerousGetHandle();
                SetValue((UIntPtr)IntPtr.Size, (IntPtr)(&handle));
            }
        }
		/// <summary>
		/// Creates the CL image from GL texture.  This can be a platfor specific operation.
		/// On some platforms, some of the parameters may be ignored.
		/// </summary>
		/// <returns>The CL image from GL texture.</returns>
		/// <param name="context">Context.</param>
		/// <param name="memFlags">Mem flags.</param>
		/// <param name="target">Target.</param>
		/// <param name="mipLevel">Mip level.</param>
		/// <param name="texturePointer">Texture pointer.</param>
		/// <param name="error">Error.</param>
		public static IMem CreateCLImageFromGLTexture(Context context, MemFlags memFlags, TextureTarget target, int mipLevel, IntPtr texturePointer, out ErrorCode error){
			#if UNITY_STANDALONE_OSX || UNITY_IPHONE
			//here, we use a function from apple (gcl) headers
			var ret = new Mem(gcl_gl_create_image_from_texture(target,new IntPtr(mipLevel),texturePointer));
			error = ErrorCode.Success;
			return ret;
			#endif
			#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_ANDROID
			//here we use the GL sharing extensions.
			return new Mem(clCreateFromGLTexture2D((context as IHandleData).Handle,memFlags,target,new IntPtr(mipLevel),texturePointer,out error));
			#endif
		}
Exemple #6
0
        public static InfoBuffer GetMemObjectInfo(Mem mem, MemInfo paramName, out ErrorCode error)
        {
            if (paramName == MemInfo.HostPtr) // Handle special case
            {
                IntPtr size = GetInfo(Cl.GetMemObjectInfo, mem, Cl.MemInfo.Size, out error).CastTo<IntPtr>();
                var buffer = new InfoBuffer(size);
                error = GetMemObjectInfo(mem, paramName, size, buffer, out size);
                if (error != ErrorCode.Success)
                    return InfoBuffer.Empty;

                return buffer;
            }

            return GetInfo(GetMemObjectInfo, mem, paramName, out error);
        }
Exemple #7
0
        static void RenameParentFunc(FuncContext fctx, int notUsed, Mem[] argv)
        {
            Context ctx = Vdbe.Context_Ctx(fctx);
            string input = Vdbe.Value_Text(argv[0]);
            string oldName = Vdbe.Value_Text(argv[1]);
            string newName = Vdbe.Value_Text(argv[2]);

            int zIdx;         // Pointer to token
            int zLeft = 0;    // Pointer to remainder of String

            TK token = 0;    // Type of token

            string output = string.Empty;
            int n; // Length of token z
            for (int z = 0; z < input.Length; z += n)
            {
                n = Parse.GetToken(input, z, ref token);
                if (token == TK.REFERENCES)
                {
                    string parent;
                    do
                    {
                        z += n;
                        n = Parse.GetToken(input, z, ref token);
                    } while (token == TK.SPACE);

                    parent = (z + n < input.Length ? input.Substring(z, n) : string.Empty);
                    if (string.IsNullOrEmpty(parent)) break;
                    Parse.Dequote(ref parent);
                    if (oldName.Equals(parent, StringComparison.OrdinalIgnoreCase))
                    {
                        string out_ = C._mtagprintf(ctx, "%s%.*s\"%w\"", output, z - zLeft, input.Substring(zLeft), newName);
                        C._tagfree(ctx, ref output);
                        output = out_;
                        z += n;
                        zLeft = z;
                    }
                    C._tagfree(ctx, ref parent);
                }
            }

            string r = C._mtagprintf(ctx, "%s%s", output, input.Substring(zLeft));
            Vdbe.Result_Text(fctx, r, -1, DESTRUCTOR.DYNAMIC);
            C._tagfree(ctx, ref output);
        }
Exemple #8
0
        public static RC MemMakeWriteable(Mem mem)
        {
            Debug.Assert(mem.Ctx == null || MutexEx.Held(mem.Ctx.Mutex));
            Debug.Assert((mem.Flags & MEM.RowSet) == 0);
            E.ExpandBlob(mem);
            MEM f = mem.Flags;
            if ((f & (MEM.Str | MEM.Blob)) != 0) //: mem->Z != mem->Malloc)
            {
                if (MemGrow(mem, mem.N + 2, true) != 0)
                    return RC.NOMEM;
                //: mem.Z[mem.N] = 0;
                //: mem.Z[mem.N + 1] = 0;
                mem.Flags |= MEM.Term;
#if DEBUG
                mem.ScopyFrom = null;
#endif
            }
            return RC.OK;
        }
Exemple #9
0
        public static RC MemGrow(Mem mem, int newSize, bool preserve)
        {
            //Debug.Assert((mem.Malloc != null && mem.Malloc == mem.Z ? 1 : 0) +
            //    ((mem.Flags & MEM.Dyn) && mem.Del ? 1 : 0) +
            //    ((mem.Flags & MEM.Ephem) ? 1 : 0) +
            //    ((mem.Flags & MEM.Static) ? 1 : 0) <= 1);
            Debug.Assert((mem.Flags & MEM.RowSet) == 0);

            // If the preserve flag is set to true, then the memory cell must already contain a valid string or blob value.
            Debug.Assert(!preserve || (mem.Flags & (MEM.Blob | MEM.Str)) != 0);

            if (newSize < 32) newSize = 32;
            //: if (_tagallocsize(mem->Ctx, mem->Malloc) < newSize)
            if (preserve) //: && mem->Z == mem->Malloc)
            {
                if (mem.Z == null)
                    mem.Z = null;
                else
                    if (newSize < mem.Z.Length)
                        mem.Z = mem.Z.Substring(0, newSize);
                preserve = false;
            }
            else
            {
                //: _tagfree(mem->Ctx, mem->Malloc);
                mem.Z = null; //: mem->Malloc = (char*)_tagalloc(mem->Ctx, newSize);
            }

            //: if (mem.Z && preserve && mem.Malloc && mem.Z != mem->Malloc)
            //:     _memcpy(mem.Malloc, mem.Z, mem.N);
            if ((mem.Flags & MEM.Dyn) != 0 && mem.Del != null)
            {
                Debug.Assert(mem.Del != C.DESTRUCTOR_DYNAMIC);
                mem.Del(mem.Z);
            }

            //: mem.Z = mem->Malloc;
            mem.Flags = (MEM)(mem.Z == null ? MEM.Null : mem.Flags & ~(MEM.Ephem | MEM.Static));
            mem.Del = null;
            return (mem.Z != null ? RC.OK : RC.NOMEM);
        }
Exemple #10
0
        public static RC ChangeEncoding(Mem mem, TEXTENCODE newEncode)
        {
            Debug.Assert((mem.Flags & MEM.RowSet) == 0);
            Debug.Assert(newEncode == TEXTENCODE.UTF8 || newEncode == TEXTENCODE.UTF16LE || newEncode == TEXTENCODE.UTF16BE);
            if ((mem.Flags & MEM.Str) == 0 || mem.Encode == newEncode)
            {
                if (mem.Z == null && mem.Z_ != null)
                    mem.Z = Encoding.UTF8.GetString(mem.Z_, 0, mem.Z_.Length);
                return RC.OK;
            }
            Debug.Assert(mem.Ctx == null || MutexEx.Held(mem.Ctx.Mutex));
#if OMIT_UTF16
            return RC.ERROR;
#else
            // MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, then the encoding of the value may not have changed.
            RC rc = MemTranslate(mem, newEncode);
            Debug.Assert(rc == RC.OK || rc == RC.NOMEM);
            Debug.Assert(rc == RC.OK || mem.Encode != newEncode);
            Debug.Assert(rc == RC.NOMEM || mem.Encode == newEncode);
            return rc;
#endif
        }
Exemple #11
0
        static void RenameTableFunc(FuncContext fctx, int notUsed, Mem[] argv)
        {
            Context ctx = Vdbe.Context_Ctx(fctx);
            string sql = Vdbe.Value_Text(argv[0]);
            string tableName = Vdbe.Value_Text(argv[1]);
            if (string.IsNullOrEmpty(sql))
                return;
            int length = 0;
            TK token = 0;
            Token tname = new Token();

            int z = 0, zLoc = 0;

            // The principle used to locate the table name in the CREATE TABLE statement is that the table name is the first non-space token that
            // is immediately followed by a TK_LP or TK_USING token.
            do
            {
                if (z == sql.Length)
                    return; // Ran out of input before finding an opening bracket. Return NULL.
                // Store the token that zCsr points to in tname.
                zLoc = z;
                tname.data = sql.Substring(z);
                tname.length = (uint)length;

                // Advance zCsr to the next token. Store that token type in 'token', and its length in 'len' (to be used next iteration of this loop).
                do
                {
                    z += length;
                    length = (z == sql.Length ? 1 : Parse.GetToken(sql, z, ref token));
                } while (token == TK.SPACE);
                Debug.Assert(length > 0);
            } while (token != TK.LP && token != TK.USING);

            string r = C._mtagprintf(ctx, "%.*s\"%w\"%s", zLoc, sql.Substring(0, zLoc), tableName, sql.Substring(zLoc + (int)tname.length));
            Vdbe.Result_Text(fctx, r, -1, DESTRUCTOR_DYNAMIC);
        }
Exemple #12
0
 private UArray(Pointer <T> p, int i)
 {
     Address = p;
     Length  = i;
     Size    = (int)Mem.GetByteCount(Length, Mem.SizeOf <T>());
 }
Exemple #13
0
		/*
		** Convert pMem so that it is of type MEM_Real.
		** Invalidate any prior representations.
		*/

		private static int sqlite3VdbeMemRealify(Mem pMem)
		{
			Debug.Assert(pMem.db == null || sqlite3_mutex_held(pMem.db.mutex));
			//assert( EIGHT_BYTE_ALIGNMENT(pMem) );

			pMem.r = sqlite3VdbeRealValue(pMem);
			MemSetTypeFlag(pMem, MEM_Real);
			return SQLITE_OK;
		}
Exemple #14
0
 public static ProgramState CreateProgram(IEnumerable <Mem> program,
                                          Mem input)
 => new ProgramState(0, program).WithInput(input);
Exemple #15
0
 public ProgramState WithOutput(Mem output)
 => new ProgramState(this.IP, this.RelativeBase,
                     this.Program, this.Input, this.Output.Push(output),
                     this.Stopped);
 protected abstract T Read(Mem memory);
 protected override void ReleaseUnmanaged()
 {
     base.ReleaseUnmanaged();
     Mem.Free(_context);
 }
Exemple #18
0
 protected override void OnUnInit()
 {
     Mem.Del(ref this._uiLabelSprite);
     Mem.Del(ref this._uiLabelSubSprite);
 }
Exemple #19
0
		} // Call w/o offset

		private static int sqlite3VdbeMemSetStr(
		Mem pMem,           /* Memory cell to set to string value */
		string z,           /* String pointer */
		int offset,         /* offset into string */
		int n,              /* Bytes in string, or negative */
		u8 enc,             /* Encoding of z.  0 for BLOBs */
		dxDel xDel//)(void*)/* Destructor function */
		)
		{
			int nByte = n;      /* New value for pMem->n */
			int iLimit;         /* Maximum allowed string or blob size */
			u16 flags = 0;      /* New value for pMem->flags */

			Debug.Assert(pMem.db == null || sqlite3_mutex_held(pMem.db.mutex));
			Debug.Assert((pMem.flags & MEM_RowSet) == 0);

			/* If z is a NULL pointer, set pMem to contain an SQL NULL. */
			if (z == null || z.Length < offset)
			{
				sqlite3VdbeMemSetNull(pMem);
				return SQLITE_OK;
			}

			if (pMem.db != null)
			{
				iLimit = pMem.db.aLimit[SQLITE_LIMIT_LENGTH];
			}
			else
			{
				iLimit = SQLITE_MAX_LENGTH;
			}
			flags = (u16)(enc == 0 ? MEM_Blob : MEM_Str);
			if (nByte < 0)
			{
				Debug.Assert(enc != 0);
				if (enc == SQLITE_UTF8)
				{
					for (nByte = 0; nByte <= iLimit && nByte < z.Length - offset && z[offset + nByte] != 0; nByte++)
					{
					}
				}
				else
				{
					for (nByte = 0; nByte <= iLimit && z[nByte + offset] != 0 || z[offset + nByte + 1] != 0; nByte += 2)
					{
					}
				}
				flags |= MEM_Term;
			}

			/* The following block sets the new values of Mem.z and Mem.xDel. It
			** also sets a flag in local variable "flags" to indicate the memory
			** management (one of MEM_Dyn or MEM_Static).
			*/
			if (xDel == SQLITE_TRANSIENT)
			{
				u32 nAlloc = (u32)nByte;
				if ((flags & MEM_Term) != 0)
				{
					nAlloc += (u32)(enc == SQLITE_UTF8 ? 1 : 2);
				}
				if (nByte > iLimit)
				{
					return SQLITE_TOOBIG;
				}
				if (sqlite3VdbeMemGrow(pMem, (int)nAlloc, 0) != 0)
				{
					return SQLITE_NOMEM;
				}
				//if ( nAlloc < z.Length )
				//pMem.z = new byte[nAlloc]; Buffer.BlockCopy( z, 0, pMem.z, 0, (int)nAlloc ); }
				//else
				if (enc == 0)
				{
					pMem.z = null;
					pMem.zBLOB = sqlite3Malloc(n);
					for (int i = 0; i < n && i < z.Length - offset; i++)
						pMem.zBLOB[i] = (byte)z[offset + i];
				}
				else
				{
					pMem.z = n > 0 && z.Length - offset > n ? z.Substring(offset, n) : z.Substring(offset);//memcpy(pMem.z, z, nAlloc);
					sqlite3_free(ref pMem.zBLOB);
				}
			}
			else if (xDel == SQLITE_DYNAMIC)
			{
				sqlite3VdbeMemRelease(pMem);
				//pMem.zMalloc = pMem.z = (char*)z;
				if (enc == 0)
				{
					pMem.z = null;
					if (pMem.zBLOB != null)
						sqlite3_free(ref pMem.zBLOB);
					pMem.zBLOB = Encoding.UTF8.GetBytes(offset == 0 ? z : z.Length + offset < n ? z.Substring(offset, n) : z.Substring(offset));
				}
				else
				{
					pMem.z = n > 0 && z.Length - offset > n ? z.Substring(offset, n) : z.Substring(offset);//memcpy(pMem.z, z, nAlloc);
					sqlite3_free(ref pMem.zBLOB);
				}
				pMem.xDel = null;
			}
			else
			{
				sqlite3VdbeMemRelease(pMem);
				if (enc == 0)
				{
					pMem.z = null;
					if (pMem.zBLOB != null)
						sqlite3_free(ref pMem.zBLOB);
					pMem.zBLOB = Encoding.UTF8.GetBytes(offset == 0 ? z : z.Length + offset < n ? z.Substring(offset, n) : z.Substring(offset));
				}
				else
				{
					pMem.z = n > 0 && z.Length - offset > n ? z.Substring(offset, n) : z.Substring(offset);//memcpy(pMem.z, z, nAlloc);
					sqlite3_free(ref pMem.zBLOB);
				}
				pMem.xDel = xDel;
				flags |= (u16)((xDel == SQLITE_STATIC) ? MEM_Static : MEM_Dyn);
			}
			pMem.n = nByte;
			pMem.flags = flags;
			pMem.enc = (enc == 0 ? SQLITE_UTF8 : enc);
			pMem.type = (enc == 0 ? SQLITE_BLOB : SQLITE_TEXT);

#if !SQLITE_OMIT_UTF16
if( pMem.enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem)!=0 ){
return SQLITE_NOMEM;
}
#endif

			if (nByte > iLimit)
			{
				return SQLITE_TOOBIG;
			}

			return SQLITE_OK;
		}
Exemple #20
0
        /*
         * private unsafe Mem GetCounter()
         * {
         *  fixed (ulong* dataptr = &voxelctr)
         *  {
         *      counter = manager.Context.CreateBuffer(MemFlags.READ_WRITE, 8, new IntPtr(dataptr));
         *  }
         *  return counter;
         * }*/

        private unsafe void DoRayCasting(BitmapData output)
        {
            try
            {
                int deviceIndex = 0;
                outputBuffer = manager.Context.CreateBuffer(MemFlags.USE_HOST_PTR, output.Stride * output.Height, output.Scan0);



                if (first || changeDistance)
                {
                    // модель камеры UVN
                    camPos = new Float4()
                    {
                        S0 =
                            vol.GetSize() / 2 - (float)Math.Cos(camAngle * Math.PI / 180) * camDist,
                        S1 = vol.GetSize() / 2,
                        S2 = vol.GetSize() / 2 - (float)Math.Sin(camAngle * Math.PI / 180) * camDist,
                        S3 = 0
                    };

                    first          = false;
                    changeDistance = false;
                    camPosOld      = camPos;
                }

                else
                {
                    // поворот вокруг оси куба визуализации
                    if (angleChange && leftChange)
                    {
                        camPosOld.S0 -= camLookAt.S0;
                        camPosOld.S2 -= camLookAt.S2;

                        camPos.S0 = (float)Math.Cos(camAngle * Math.PI / 180) * camPosOld.S0 + (float)Math.Sin(camAngle * Math.PI / 180) * camPosOld.S2;
                        camPos.S1 = vol.GetSize() / 2;
                        camPos.S2 = -(float)Math.Sin(camAngle * Math.PI / 180) * camPosOld.S0 + (float)Math.Cos(camAngle * Math.PI / 180) * camPosOld.S2;
                        camPos.S3 = 0;

                        camPos.S0 += camLookAt.S0;
                        camPos.S2 += camLookAt.S2;

                        camPosOld   = camPos;
                        angleChange = false;
                        leftChange  = false;
                    }
                    if (angleChange && rightChange)
                    {
                        camPosOld.S0 -= camLookAt.S0;
                        camPosOld.S2 -= camLookAt.S2;

                        camPos.S0 = (float)Math.Cos(camAngle * Math.PI / 180) * camPosOld.S0 - (float)Math.Sin(camAngle * Math.PI / 180) * camPosOld.S2;
                        camPos.S1 = vol.GetSize() / 2;
                        camPos.S2 = (float)Math.Sin(camAngle * Math.PI / 180) * camPosOld.S0 + (float)Math.Cos(camAngle * Math.PI / 180) * camPosOld.S2;
                        camPos.S3 = 0;

                        camPos.S0 += camLookAt.S0;
                        camPos.S2 += camLookAt.S2;

                        camPosOld   = camPos;
                        angleChange = false;
                        leftChange  = false;
                    }
                }

                camLookAt = new Float4()
                {
                    S0 = vol.GetSize() / camfactorX,
                    S1 = vol.GetSize() / camfactorX,
                    S2 = vol.GetSize() / camfactorZ,
                    S3 = 0
                };

                //light = camPos;

                // направление камеры, UVN модель
                camForward = camLookAt.Sub(camPos).Normalize(); // направление просмотра
                var up    = new Float4(0.0f, 1.0f, 0.0f, 0.0f);
                var right = MathClass.Cross(up, camForward).Normalize().Times(1.5f);
                up = MathClass.Cross(camForward, right).Normalize().Times(-1.5f);



                /*  обработка выходного изображения BitmapData в OpenCl устройстве */
                for (var x = 0; x < output.Width; x += blocksize)
                {
                    for (var y = 0; y < output.Height; y += blocksize)
                    {
                        var rayTracingGlobalWorkSize = new IntPtr[2]; // work_dim = 2
                        rayTracingGlobalWorkSize[0] = (IntPtr)(output.Width - x > blocksize ? blocksize : output.Width - x);
                        rayTracingGlobalWorkSize[1] = (IntPtr)(output.Height - y > blocksize ? blocksize : output.Height - y);

                        var rayTracingGlobalOffset = new IntPtr[2];
                        rayTracingGlobalOffset[0] = (IntPtr)x;
                        rayTracingGlobalOffset[1] = (IntPtr)y;

                        float ka  = (float)(Convert.ToDouble(kamb.Text));
                        float kd  = (float)(Convert.ToDouble(kdiff.Text));
                        float ks  = (float)(Convert.ToDouble(kspec.Text));
                        float exp = (float)(Convert.ToDouble(specexp.Text));

                        float kkc = (float)(Convert.ToDouble(this.kc.Text));
                        float kkl = (float)(Convert.ToDouble(this.kl.Text));
                        float kkq = (float)(Convert.ToDouble(this.kq.Text));

                        /* передали аргументы в kernel функцию */
                        kernel.SetArg(0, output.Width);
                        kernel.SetArg(1, output.Height);
                        kernel.SetArg(2, outputBuffer);  // в ядре с global, поскольку для выполнения требуется доступ к output
                        kernel.SetArg(3, output.Stride);
                        kernel.SetArg(4, camPos);
                        kernel.SetArg(5, camForward);
                        kernel.SetArg(6, right);
                        kernel.SetArg(7, up);
                        kernel.SetArg(8, vol.CreateBuffer());
                        kernel.SetArg(9, vol.GetSize());
                        kernel.SetArg(10, light);
                        kernel.SetArg(11, boxMinCon);
                        kernel.SetArg(12, boxMaxCon);
                        kernel.SetArg(13, Convert.ToInt16(colorMi.Text));
                        kernel.SetArg(14, Convert.ToInt16(colorMa.Text));
                        kernel.SetArg(15, _cutArrea.Checked ? (short)1 : (short)0);
                        kernel.SetArg(16, _trilinear.Checked ? (short)1 : (short)0);
                        kernel.SetArg(17, tf.Checked ? (short)1: (short)0);
                        kernel.SetArg(18, GetColors());
                        kernel.SetArg(19, winWidth_vox);
                        kernel.SetArg(20, winCentre_vox);
                        kernel.SetArg(21, form_this.knots_counter);
                        kernel.SetArg(22, Convert.ToInt16(colorMi2.Text));
                        kernel.SetArg(23, Convert.ToInt16(colorMa2.Text));
                        kernel.SetArg(24, GetOpacity());
                        kernel.SetArg(25, ka);
                        kernel.SetArg(26, kd);
                        kernel.SetArg(27, ks);
                        kernel.SetArg(28, exp);
                        kernel.SetArg(29, kkc);
                        kernel.SetArg(30, kkl);
                        kernel.SetArg(31, kkq);
                        //kernel.SetArg(32, GetCounter());

                        /* Ставит в очередь команду для исполнения kernel на устройстве */

                        /*
                         *  rayTracingGlobalOffset -
                         *  globalWorkOffset: может использоваться для указания массива значений
                         *  размерности work_dim unsigned который описывает смещение используемое для расчета  global ID  work-item
                         *  вместо того чтобы global IDs всегда начинался со смещение (0, 0,... 0).
                         *
                         *  rayTracingGlobalWorkSize -
                         *  globalWorkSize: общее число global work-items вычисляется как global_work_size[0] *...* global_work_size[work_dim - 1].
                         *
                         */
                        manager.CQ[deviceIndex].EnqueueNDRangeKernel(kernel, 2, rayTracingGlobalOffset, rayTracingGlobalWorkSize, null);
                    }
                }

                /* подождали пока все work-items выполнятся */
                manager.CQ[deviceIndex].EnqueueBarrier();

                /* для того чтобы получить доступ к памяти и записать в выходное изображение мы просим у OpenCL *наложить* данные в хост-устройство */
                IntPtr p = manager.CQ[deviceIndex].EnqueueMapBuffer(outputBuffer, true, MapFlags.READ, IntPtr.Zero, (IntPtr)(output.Stride * output.Height));
                //IntPtr z = manager.CQ[deviceIndex].EnqueueMapBuffer(counter, true, MapFlags.READ_WRITE, IntPtr.Zero, (IntPtr)(sizeof(ulong)));

                /* когда мы заканчиваем работать с буфером надо вызвать эту функцию */
                manager.CQ[deviceIndex].EnqueueUnmapMemObject(outputBuffer, p);
                //manager.CQ[deviceIndex].EnqueueUnmapMemObject(counter, z);
                manager.CQ[deviceIndex].Finish();
                realctr          += voxelctr;
                voxelCounter.Text = Convert.ToString(realctr);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ray casting exception:" + ex.Message, "Exception");
                //Environment.Exit(-1);
            }
            finally
            {
                if (outputBuffer != null)
                {
                    outputBuffer.Dispose();
                }
            }
        }
Exemple #21
0
        public VoxelImage()
        {
            InitializeComponent();
            first          = true;
            angleChange    = false;
            changeDistance = false;
            leftChange     = false;
            rightChange    = false;
            voxelctr       = 0;
            realctr        = 0;

            this.lx.Text = Convert.ToString(light.S0);
            this.ly.Text = Convert.ToString(light.S1);
            this.lz.Text = Convert.ToString(light.S2);


            this.trackminX.SetRange(0, 512);
            this.trackminY.SetRange(0, 512);
            this.trackminZ.SetRange(0, 512);
            this.trackmaxX.SetRange(0, 512);
            this.trackmaxY.SetRange(0, 512);
            this.trackmaxZ.SetRange(0, 512);


            this.trackminX.Value = (int)(boxMinCon.S0);
            this.trackminY.Value = (int)(boxMinCon.S1);
            this.trackminZ.Value = (int)(boxMinCon.S2);

            this.trackmaxX.Value = (int)(boxMaxCon.S0);
            this.trackmaxY.Value = (int)(boxMaxCon.S1);
            this.trackmaxZ.Value = (int)(boxMaxCon.S2);


            this.minX.Text  = Convert.ToString(boxMinCon.S0);
            this.minY.Text  = Convert.ToString(boxMinCon.S1);
            this.minZ.Text  = Convert.ToString(boxMinCon.S2);
            this.maxX.Text  = Convert.ToString(boxMaxCon.S0);
            this.maxY.Text  = Convert.ToString(boxMaxCon.S1);
            this.maxZ.Text  = Convert.ToString(boxMaxCon.S2);
            this.kamb.Text  = Convert.ToString(0.1);
            this.kdiff.Text = Convert.ToString(0.5);
            this.kspec.Text = Convert.ToString(0.4);

            this.tracklx.SetRange(-1000, 1000);
            this.trackly.SetRange(-1000, 1000);
            this.tracklz.SetRange(-1000, 1000);

            this.tracklx.Value = (int)light.S0;
            this.trackly.Value = (int)light.S1;
            this.tracklz.Value = (int)light.S2;

            this.kc.Text = "1,0";
            this.kl.Text = "0,0";
            this.kq.Text = "0,0";

            this.specexp.Text = "1,0";

            outputBuffer = null;
            color_buffer = null;
            opacity      = null;

            clock = new Stopwatch();
        }
Exemple #22
0
 private void OnDestroy()
 {
     Mem.Del(ref _taTexture);
 }
Exemple #23
0
 public Cheats(Mem garouMem)
 {
     this.garouMem = garouMem;
 }
 protected override void Write(float value, Mem memory)
 {
     memory.writeBytes(this.address, BitConverter.GetBytes(value));
 }
Exemple #25
0
		/*
** Delete any previous value and set the value stored in pMem to NULL.
*/

		private static void sqlite3VdbeMemSetNull(Mem pMem)
		{
			if ((pMem.flags & MEM_Frame) != 0)
			{
				VdbeFrame pFrame = pMem.u.pFrame;
				pFrame.pParent = pFrame.v.pDelFrame;
				pFrame.v.pDelFrame = pFrame;
			}
			if ((pMem.flags & MEM_RowSet) != 0)
			{
				sqlite3RowSetClear(pMem.u.pRowSet);
			}
			MemSetTypeFlag(pMem, MEM_Null);
			sqlite3_free(ref pMem.zBLOB);
			pMem.z = null;
			pMem.type = SQLITE_NULL;
		}
 /*
 ** Clear any existing type flags from a Mem and replace them with f
 */
 //#define MemSetTypeFlag(p, f) \
 //   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
 static void MemSetTypeFlag(Mem p, int f)
 {
     p.flags = (u16)(p.flags & ~(MEM_TypeMask | MEM_Zero) | f);
 }// TODO -- Convert back to inline for speed
 protected override float Read(Mem memory)
 {
     byte[] bytearray = memory.readBytes(this.address, 4);
     return(BitConverter.ToSingle(bytearray, 0));
 }
        }// TODO -- Convert back to inline for speed

        /*
        ** Return true if a memory cell is not marked as invalid.  This macro
        ** is for use inside Debug.Assert() statements only.
        */
#if SQLITE_DEBUG
        //#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
        static bool memIsValid(Mem M)
        {
            return(((M).flags & MEM_Invalid) == 0);
        }
Exemple #29
0
 static void sqlite3_free( ref Mem p )
 {
   if ( p == null ) return;
   if ( sqlite3GlobalConfig.bMemstat )
   {
     sqlite3_mutex_enter( mem0.mutex );
     //sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) );
     sqlite3GlobalConfig.m.xFreeMem( ref p );
     sqlite3_mutex_leave( mem0.mutex );
   }
   else
   {
     sqlite3GlobalConfig.m.xFreeMem( ref p );
   }
   p = null;
 }
 static bool memIsValid(Mem M)
 {
     return(true);
 }
 public LZ4FastEncoder(int blockSize, int extraBlocks = 0) :
     base(blockSize, extraBlocks)
 {
     _context = (LZ4Context *)Mem.AllocZero(sizeof(LZ4Context));
 }
Exemple #32
0
		/*
** Delete any previous value and set the value to be a BLOB of length
** n containing all zeros.
*/

		private static void sqlite3VdbeMemSetZeroBlob(Mem pMem, int n)
		{
			sqlite3VdbeMemRelease(pMem);
			pMem.flags = MEM_Blob | MEM_Zero;
			pMem.type = SQLITE_BLOB;
			pMem.n = 0;
			if (n < 0)
				n = 0;
			pMem.u.nZero = n;
			pMem.enc = SQLITE_UTF8;
#if SQLITE_OMIT_INCRBLOB
			sqlite3VdbeMemGrow(pMem, n, 0);
			//if( pMem.z!= null ){
			pMem.n = n;
			pMem.z = null;//memset(pMem.z, 0, n);
			pMem.zBLOB = sqlite3Malloc(n);
			//}
#endif
		}
Exemple #33
0
        public static bool ServerTittle(string MapName, string ModeName)
        {
            Regex rgx = new Regex(@"^gn\\IW5\\gt\\([^\\].*?\\){27}$");

            Action <Action <List <IntPtr> > > FindAddr = (callback) =>
            {
                PrintLog("ServerTittle::  start scanning...");

                // We'll use threading to avoid LAGGGGGS
                Thread _thr = new Thread(() =>
                {
                    callback(new AobScan().Scan(new byte[] { 0x67, 0x6E, 0x5C, 0x49, 0x57, 0x35, 0x5C, 0x67, 0x74, 0x5C }));
                });

                // start the search thread
                _thr.Start();
            };

            //Filter the addrs
            Func <List <IntPtr>, List <IntPtr> > Filter = (addrs) =>
            {
                List <IntPtr> pass1 = new List <IntPtr>();


                // step 1. - lower than 0xC000000, should match pattern
                addrs.ForEach(addr =>
                {
                    if ((int)addr <= 0xC000000)
                    {
                        string structure = Mem.ReadString((int)addr, 128);
                        Match match      = rgx.Match(structure);
                        if (match.Success)
                        {
                            pass1.Add(addr);
                        }
                    }
                });

                List <IntPtr> pass2 = new List <IntPtr>();

                PrintLog("ServerTittle::  addrs: " + String.Join(", ", pass1.ConvertAll <string>((s) => { return("0x" + (s.ToInt32().ToString("X"))); }).ToArray()));

                //step 2.  (black magic)
                int gap_min = 0x700, gap_max = 0x7FF;
                if (pass1.Count < 2)
                {
                    return(pass2);
                }
                else
                {
                    int[] _addrs = pass1.ConvertAll(s => { return((int)s); }).ToArray();
                    for (int i = 1; i < _addrs.Length; i++)
                    {
                        if (((_addrs[i] - _addrs[i - 1]) >= gap_min) && ((_addrs[i] - _addrs[i - 1]) <= gap_max))
                        {
                            pass2.Add(addrs[i]);
                            return(pass2);
                        }
                    }
                }

                return(pass2);
            };

            Action <IntPtr> Write = (addr) =>
            {
                Func <string, string> construct = (_structure) =>
                {
                    // no, Carl, this is not a brainfuck
                    Regex _rgx  = new Regex(@"^(gn\\IW5\\gt\\)([^\\].*?)\\(([^\\].*?\\){5})([^\\].*?)\\(([^\\].*?\\){20})$");
                    Match match = _rgx.Match(_structure);

                    /*
                     * restore default map & mode strings in this case
                     * ConfigValues.mapname == Call<string>("getdvar", mapname);
                     * ConfigValues.g_gametype == Call<string>("getdvar", g_gametype);
                     */
                    ModeName = String.IsNullOrEmpty(ModeName) ? GSCFunctions.GetDvar("g_gametype") : ModeName;
                    MapName  = String.IsNullOrEmpty(MapName) ? GSCFunctions.GetDvar("mapname") : MapName;

                    _structure = match.Groups[1].Value + ModeName + "\\" + match.Groups[3].Value + MapName + "\\" + match.Groups[6].Value;
                    return(_structure);
                };

                if ((int)addr <= 0)
                {
                    return;
                }
                if (MapName.Length > 28)
                {
                    PrintLog("ServerTittle::  MapName overflow. Max length is 28 chars!");
                    MapName = MapName.Substring(0, 28);
                }
                if (ModeName.Length > 15)
                {
                    PrintLog("ServerTittle::  ModeName overflow. Max length is 15 chars!");
                    ModeName = ModeName.Substring(0, 15);
                }
                string structure = Mem.ReadString((int)addr, 128);
                if (!rgx.Match(structure).Success)
                {
                    return;
                }

                structure = construct(structure);
                if ((structure.Length >= 128) && (MapName.Length > 20))
                {
                    //maybe it will help...
                    MapName   = MapName.Substring(0, 20);
                    structure = construct(structure);
                }

                List <byte> data = Encoding.ASCII.GetBytes(structure).ToList();
                data.Add(0);
                if (data.Count <= 128)
                {
                    (new AobScan()).WriteMem((int)addr, data.ToArray());
                }
                else
                {
                    PrintLog(String.Format("ServerTittle::  structure overflow 128, but got {0} bytes.", data.Count.ToString()));
                }
            };

            /* Once found, the address wont change in future
             * so we'll store it as a server dvar
             */
            string sv_serverinfo_addr = GSCFunctions.GetDvar("sv_serverinfo_addr");

            if (String.IsNullOrEmpty(sv_serverinfo_addr)) //first start
            {
                // find teh addrs
                FindAddr(new Action <List <IntPtr> >((addrs) =>
                {
                    addrs = Filter(addrs);
                    PrintLog("ServerTittle::  addrs(filter): " + String.Join(", ", addrs.ConvertAll <string>((s) => { return("0x" + (s.ToInt32().ToString("X"))); }).ToArray()));

                    if (addrs.Count == 1)
                    {
                        IntPtr addr = addrs.First();

                        //save found address
                        GSCFunctions.SetDvar("sv_serverinfo_addr", new Parameter((int)addr.ToInt32()));

                        Write(addr);
                    }
                    else
                    {
                        PrintLog("ServerTittle::  structure not found");
                        GSCFunctions.SetDvar("sv_serverinfo_addr", new Parameter((int)0)); //addr no found, skip search in future
                    }
                    PrintLog("ServerTittle::  done scanning.");
                }));
            }
            else
            {
                Thread _thr = new Thread(() =>
                {
                    Thread.Sleep(1000); // in case of fast restart, default AfterInterval will be ignored

                    //skip search, just load from sdvar
                    int addr = int.Parse(sv_serverinfo_addr);
                    if (addr > 0)
                    {
                        PrintLog("ServerTittle::  addr: 0x" + addr.ToString("X"));
                        Write(new IntPtr(addr));
                    }
                });

                _thr.Start();
            }

            return(false);
        }
Exemple #34
0
		/*
		** Delete any previous value and set the value stored in pMem to val,
		** manifest type REAL.
		*/

		private static void sqlite3VdbeMemSetDouble(Mem pMem, double val)
		{
			if (sqlite3IsNaN(val))
			{
				sqlite3VdbeMemSetNull(pMem);
			}
			else
			{
				sqlite3VdbeMemRelease(pMem);
				pMem.r = val;
				pMem.flags = MEM_Real;
				pMem.type = SQLITE_FLOAT;
			}
		}
Exemple #35
0
 public ProgramState Write(Adr adr, Mem value)
 => this.WithProgram(this.Program.SetItem(adr, value));
Exemple #36
0
		/*
		** Return true if the Mem object contains a TEXT or BLOB that is
		** too large - whose size exceeds p.db.aLimit[SQLITE_LIMIT_LENGTH].
		*/

		private static bool sqlite3VdbeMemTooBig(Mem p)
		{
			//Debug.Assert( p.db != null );
			if ((p.flags & (MEM_Str | MEM_Blob)) != 0)
			{
				int n = p.n;
				if ((p.flags & MEM_Zero) != 0)
				{
					n += p.u.nZero;
				}
				return n > p.db.aLimit[SQLITE_LIMIT_LENGTH];
			}
			return false;
		}
Exemple #37
0
 public ProgramState WithInput(Mem input, params Mem[] more)
 => new ProgramState(this.IP, this.RelativeBase, this.Program,
                     more.Aggregate(this.Input.Enqueue(input),
                                    (accu, current) => accu.Enqueue(current)),
                     this.Output, false);
Exemple #38
0
		/*
** Size of struct Mem not including the Mem.zMalloc member.
*/
		//#define MEMCELLSIZE (size_t)(&(((Mem *)0).zMalloc))

		/*
		** Make an shallow copy of pFrom into pTo.  Prior contents of
		** pTo are freed.  The pFrom.z field is not duplicated.  If
		** pFrom.z is used, then pTo.z points to the same thing as pFrom.z
		** and flags gets srcType (either MEM_Ephem or MEM_Static).
		*/

		private static void sqlite3VdbeMemShallowCopy(Mem pTo, Mem pFrom, int srcType)
		{
			Debug.Assert((pFrom.flags & MEM_RowSet) == 0);
			sqlite3VdbeMemReleaseExternal(pTo);
			pFrom.CopyTo(ref pTo);//  memcpy(pTo, pFrom, MEMCELLSIZE);
			pTo.xDel = null;
			if ((pFrom.flags & MEM_Static) != 0)
			{
				pTo.flags = (u16)(pFrom.flags & ~(MEM_Dyn | MEM_Static | MEM_Ephem));
				Debug.Assert(srcType == MEM_Ephem || srcType == MEM_Static);
				pTo.flags |= (u16)srcType;
			}
		}
Exemple #39
0
        public void GeneralTest()
        {
            // Lets say we have N integers and we want to square their values.
            int    N = 10000;
            Random r = new Random();

            int[] inputArray = Enumerable.Range(0, N).Select(n => r.Next(100)).ToArray();

            // Lets choose a platform (AMD, NVidia, Intel, etc..)
            Platform platform = null;

            foreach (var p in Platform.GetPlatforms())
            {
                if (Regex.IsMatch(p.Version, "^OpenCL (1.[12]|2.[01]).*$"))
                {
                    platform = p;
                    break;
                }
            }
            if (platform == null)
            {
                throw new PlatformNotSupportedException("No OpenCL platform found.");
            }

            // Lets pick a device to use from that platform. We can filter by CPU, GPU, etc...
            Device device = platform.GetDevices(DeviceType.Gpu)[0];

            // Setup Context and CommandQueue
            Context      context      = Context.Create(device);
            CommandQueue commandQueue = context.CreateCommandQueue(device);

            // Create and build a program from our OpenCL-C sourcePtr code
            string source =
                @"__kernel void square(
 __global int* input, __global int* output)
{
    size_t i = get_global_id( 0);
    output[i] = input[i] * input[i];
}";
            Program program = context.CreateProgramWithSource(source);

            program.Build();

            // Create a kernel from our program
            Kernel kernel = program.CreateKernel("square");

            // Allocate input and output buffers, and fill the input with data
            Mem input  = context.CreateBuffer(MemoryFlags.ReadOnly, N * sizeof(int));
            Mem output = context.CreateBuffer(MemoryFlags.WriteOnly, N * sizeof(int));

            // Copy our host buffer of random values to the input device buffer
            commandQueue.EnqueueWriteBuffer(input, true, inputArray);

            // Get the maximum number of work items supported for this kernel on this device
            ulong local = kernel.GetWorkGroupSize(device);

            // Set the arguments to our kernel, and enqueue it for execution
            kernel.Arguments[0].SetValue(input);
            kernel.Arguments[1].SetValue(output);
            commandQueue.EnqueueNDRangeKernel(kernel, N, 256);

            // Force the command queue to get processed, wait until all commands are complete
            commandQueue.Finish();

            // Read back the results
            int[]  results = new int[N];
            IntPtr dest    = Marshal.AllocHGlobal(N * 4);

            commandQueue.EnqueueReadBufferAndWait(output, dest, N * 4);
            Marshal.Copy(dest, results, 0, results.Length);

            // Validate our results
            int correct = 0;

            for (int i = 0; i < N; i++)
            {
                correct += (results[i] == inputArray[i] * inputArray[i]) ? 1 : 0;
            }

            Assert.AreEqual(correct, N);
        }
Exemple #40
0
		/*
		** Transfer the contents of pFrom to pTo. Any existing value in pTo is
		** freed. If pFrom contains ephemeral data, a copy is made.
		**
		** pFrom contains an SQL NULL when this routine returns.
		*/

		private static void sqlite3VdbeMemMove(Mem pTo, Mem pFrom)
		{
			Debug.Assert(pFrom.db == null || sqlite3_mutex_held(pFrom.db.mutex));
			Debug.Assert(pTo.db == null || sqlite3_mutex_held(pTo.db.mutex));
			Debug.Assert(pFrom.db == null || pTo.db == null || pFrom.db == pTo.db);
			sqlite3VdbeMemRelease(pTo);
			pFrom.CopyTo(ref pTo);// memcpy(pTo, pFrom, Mem).Length;
			pFrom.flags = MEM_Null;
			pFrom.xDel = null;
			pFrom.z = null;
			sqlite3_free(ref pFrom.zBLOB); //pFrom.zMalloc=0;
		}
Exemple #41
0
		/*
		** Convert pMem so that it has types MEM_Real or MEM_Int or both.
		** Invalidate any prior representations.
		**
		** Every effort is made to force the conversion, even if the input
		** is a string that does not look completely like a number.  Convert
		** as much of the string as we can and ignore the rest.
		*/

		private static int sqlite3VdbeMemNumerify(Mem pMem)
		{
			if ((pMem.flags & (MEM_Int | MEM_Real | MEM_Null)) == 0)
			{
				Debug.Assert((pMem.flags & (MEM_Blob | MEM_Str)) != 0);
				Debug.Assert(pMem.db == null || sqlite3_mutex_held(pMem.db.mutex));
				if ((pMem.flags & MEM_Blob) != 0 && pMem.z == null)
				{
					if (0 == sqlite3Atoi64(Encoding.UTF8.GetString(pMem.zBLOB, 0, pMem.zBLOB.Length), ref pMem.u.i, pMem.n, pMem.enc))
						MemSetTypeFlag(pMem, MEM_Int);
					else
					{
						pMem.r = sqlite3VdbeRealValue(pMem);
						MemSetTypeFlag(pMem, MEM_Real);
						sqlite3VdbeIntegerAffinity(pMem);
					}
				}
				else if (0 == sqlite3Atoi64(pMem.z, ref pMem.u.i, pMem.n, pMem.enc))
				{
					MemSetTypeFlag(pMem, MEM_Int);
				}
				else
				{
					pMem.r = sqlite3VdbeRealValue(pMem);
					MemSetTypeFlag(pMem, MEM_Real);
					sqlite3VdbeIntegerAffinity(pMem);
				}
			}
			Debug.Assert((pMem.flags & (MEM_Int | MEM_Real | MEM_Null)) != 0);
			pMem.flags = (ushort)(pMem.flags & ~(MEM_Str | MEM_Blob));
			return SQLITE_OK;
		}
Exemple #42
0
		} // Call w/o offset

		private static int sqlite3VdbeMemSetBlob(
		Mem pMem,           /* Memory cell to set to string value */
		byte[] zBlob,       /* Blob pointer */
		int offset,         /* offset into string */
		int n,              /* Bytes in string, or negative */
		u8 enc,             /* Encoding of z.  0 for BLOBs */
		dxDel xDel//)(void*)/* Destructor function */
		)
		{
			int nByte = n;      /* New value for pMem->n */
			int iLimit;         /* Maximum allowed string or blob size */

			Debug.Assert(pMem.db == null || sqlite3_mutex_held(pMem.db.mutex));
			Debug.Assert((pMem.flags & MEM_RowSet) == 0);

			/* If zBlob is a NULL pointer, set pMem to contain an SQL NULL. */
			if (zBlob == null || zBlob.Length < offset)
			{
				sqlite3VdbeMemSetNull(pMem);
				return SQLITE_OK;
			}

			if (pMem.db != null)
			{
				iLimit = pMem.db.aLimit[SQLITE_LIMIT_LENGTH];
			}
			else
			{
				iLimit = SQLITE_MAX_LENGTH;
			}
			if (nByte < 0)
			{
				Debug.Assert(enc != 0);
				if (enc == SQLITE_UTF8)
				{
					for (nByte = 0; nByte <= iLimit && nByte < zBlob.Length - offset && zBlob[offset + nByte] != 0; nByte++)
					{
					}
				}
				else
				{
					for (nByte = 0; nByte <= iLimit && zBlob[nByte + offset] != 0 || zBlob[offset + nByte + 1] != 0; nByte += 2)
					{
					}
				}
			}

			/* The following block sets the new values of Mem.z and Mem.xDel. It
			** also sets a flag in local variable "flags" to indicate the memory
			** management (one of MEM_Dyn or MEM_Static).
			*/
			Debug.Assert(enc == 0);
			{
				pMem.z = null;
				pMem.zBLOB = sqlite3Malloc(n);
				Buffer.BlockCopy(zBlob, offset, pMem.zBLOB, 0, n);
			}
			pMem.n = nByte;
			pMem.flags = MEM_Blob | MEM_Term;
			pMem.enc = (enc == 0 ? SQLITE_UTF8 : enc);
			pMem.type = (enc == 0 ? SQLITE_BLOB : SQLITE_TEXT);

			if (nByte > iLimit)
			{
				return SQLITE_TOOBIG;
			}

			return SQLITE_OK;
		}
        //int sqlite3VdbeMemTranslate(Mem*, u8);
        //#if SQLITE_DEBUG
        //  void sqlite3VdbePrintSql(Vdbe);
        //  void sqlite3VdbeMemPrettyPrint(Mem pMem, string zBuf);
        //#endif
        //int sqlite3VdbeMemHandleBom(Mem pMem);

#if NOT_SQLITE_OMIT_INCRBLOB //#if !SQLITE_OMIT_INCRBLOB
//  int sqlite3VdbeMemExpandBlob(Mem );
#else
        //  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
        static int sqlite3VdbeMemExpandBlob(Mem x)
        {
            return(SQLITE_OK);
        }
 protected abstract void Write(T value, Mem memory);
Exemple #45
0
		/*
		** Delete any previous value and set the value stored in pMem to val,
		** manifest type INTEGER.
		*/

		private static void sqlite3VdbeMemSetInt64(Mem pMem, i64 val)
		{
			sqlite3VdbeMemRelease(pMem);
			pMem.u.i = val;
			pMem.flags = MEM_Int;
			pMem.type = SQLITE_INTEGER;
		}
Exemple #46
0
        private unsafe void ExecuteKernel(Context context, Device device, CommandQueue commandQueue, Kernel kernel, float[] input, float[] output, int globalWorkSize, int localWorkSize, bool warming, bool useHostPointer, bool autoGroupSize, bool enableProfiling,
                                          out TimeSpan stopwatchTime, out TimeSpan profiledTime, out TimeSpan readTime)
        {
            MemoryFlags inFlags  = (useHostPointer ? MemoryFlags.UseHostPointer : MemoryFlags.CopyHostPointer) | MemoryFlags.ReadOnly;
            MemoryFlags outFlags = (useHostPointer ? MemoryFlags.UseHostPointer : MemoryFlags.CopyHostPointer) | MemoryFlags.ReadWrite;

            int taskSize = input.Length;

            // allocate buffers
            fixed(float *pinput = input, poutput = output)
            {
                using (Mem inputBuffer = context.CreateBuffer(inFlags, sizeof(float) * taskSize, (IntPtr)pinput),
                       outputBuffer = context.CreateBuffer(outFlags, sizeof(float) * taskSize, (IntPtr)poutput))
                {
                    kernel.Arguments[0].SetValue(inputBuffer);
                    kernel.Arguments[1].SetValue(outputBuffer);

                    Console.WriteLine("Original global work size {0}", globalWorkSize);
                    Console.WriteLine("Original local work size {0}", localWorkSize);
                    if (autoGroupSize)
                    {
                        Console.WriteLine("Run-time determines optimal workgroup size");
                    }

                    ulong workGroupSizeMaximum = kernel.GetWorkGroupSize(device);
                    Console.WriteLine("Maximum workgroup size for this kernel  {0}", workGroupSizeMaximum);

                    if (warming)
                    {
                        Console.Write("Warming up OpenCL execution...");
                        commandQueue.EnqueueNDRangeKernel(kernel, new[] { (IntPtr)globalWorkSize }, autoGroupSize ? null : new[] { (IntPtr)localWorkSize });
                        commandQueue.Finish();
                        Console.WriteLine("Done");
                    }

                    Console.Write("Executing OpenCL kernel...");
                    Stopwatch timer = Stopwatch.StartNew();
                    // execute kernel, pls notice autoGroupSize
                    using (Event perfEvent = commandQueue.EnqueueNDRangeKernel(kernel, new[] { (IntPtr)globalWorkSize }, autoGroupSize ? null : new[] { (IntPtr)localWorkSize }))
                    {
                        Event.WaitAll(perfEvent);
                        stopwatchTime = timer.Elapsed;

                        Console.WriteLine("Done");

                        if (enableProfiling)
                        {
                            ulong start = perfEvent.CommandStartTime;
                            ulong end   = perfEvent.CommandEndTime;
                            // a tick is 100ns
                            profiledTime = TimeSpan.FromTicks((long)(end - start) / 100);
                        }
                        else
                        {
                            profiledTime = TimeSpan.Zero;
                        }
                    }

                    timer.Restart();
                    if (useHostPointer)
                    {
                        IntPtr tmpPtr;
                        commandQueue.EnqueueMapBuffer(outputBuffer, true, MapFlags.Read, 0, sizeof(float) * taskSize, out tmpPtr);
                        Assert.AreEqual((IntPtr)poutput, tmpPtr, "EnqueueMapBuffer failed to return original pointer");
                        commandQueue.EnqueueUnmapMemObject(outputBuffer, tmpPtr);
                    }
                    else
                    {
                        commandQueue.EnqueueReadBufferAndWait(outputBuffer, (IntPtr)poutput, sizeof(float) * taskSize);
                    }

                    commandQueue.Finish();
                    readTime = timer.Elapsed;
                }
            }
        }
Exemple #47
0
		/*
		** Delete any previous value and set the value of pMem to be an
		** empty boolean index.
		*/

		private static void sqlite3VdbeMemSetRowSet(Mem pMem)
		{
			sqlite3 db = pMem.db;
			Debug.Assert(db != null);
			Debug.Assert((pMem.flags & MEM_RowSet) == 0);
			sqlite3VdbeMemRelease(pMem);
			//pMem.zMalloc = sqlite3DbMallocRaw( db, 64 );
			//if ( db.mallocFailed != 0 )
			//{
			//  pMem.flags = MEM_Null;
			//}
			//else
			{
				//Debug.Assert( pMem.zMalloc );
				pMem.u.pRowSet = new RowSet(db, 5);// sqlite3RowSetInit( db, pMem.zMalloc,
				//     sqlite3DbMallocSize( db, pMem.zMalloc ) );
				Debug.Assert(pMem.u.pRowSet != null);
				pMem.flags = MEM_RowSet;
			}
		}
 /// <inheritdoc />
 protected override void ReleaseUnmanaged()
 {
     base.ReleaseUnmanaged();
     Mem.Free(_inputBuffer);
 }
Exemple #49
0
		/*
** This routine prepares a memory cell for modication by breaking
** its link to a shallow copy and by marking any current shallow
** copies of this cell as invalid.
**
** This is used for testing and debugging only - to make sure shallow
** copies are not misused.
*/

		private static void sqlite3VdbeMemPrepareToChange(Vdbe pVdbe, Mem pMem)
		{
			int i;
			Mem pX;
			for (i = 1; i <= pVdbe.nMem; i++)
			{
				pX = pVdbe.aMem[i];
				if (pX.pScopyFrom == pMem)
				{
					pX.flags |= MEM_Invalid;
					pX.pScopyFrom = null;
				}
			}
			pMem.pScopyFrom = null;
		}
 private void OnDestroy()
 {
     Mem.Del(ref _psExplosion);
 }
Exemple #51
0
		/*
		** Make a full copy of pFrom into pTo.  Prior contents of pTo are
		** freed before the copy is made.
		*/

		private static int sqlite3VdbeMemCopy(Mem pTo, Mem pFrom)
		{
			int rc = SQLITE_OK;

			Debug.Assert((pFrom.flags & MEM_RowSet) == 0);
			sqlite3VdbeMemReleaseExternal(pTo);
			pFrom.CopyTo(ref pTo);// memcpy(pTo, pFrom, MEMCELLSIZE);
			pTo.flags = (u16)(pTo.flags & ~MEM_Dyn);

			if ((pTo.flags & (MEM_Str | MEM_Blob)) != 0)
			{
				if (0 == (pFrom.flags & MEM_Static))
				{
					pTo.flags |= MEM_Ephem;
					rc = sqlite3VdbeMemMakeWriteable(pTo);
				}
			}

			return rc;
		}
Exemple #52
0
 static Mem sqlite3MemMallocMem(Mem pMem)
 {
     return(new Mem());
 }
Exemple #53
0
		/*
		** Change the value of a Mem to be a string or a BLOB.
		**
		** The memory management strategy depends on the value of the xDel
		** parameter. If the value passed is SQLITE_TRANSIENT, then the
		** string is copied into a (possibly existing) buffer managed by the
		** Mem structure. Otherwise, any existing buffer is freed and the
		** pointer copied.
		**
		** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
		** size limit) then no memory allocation occurs.  If the string can be
		** stored without allocating memory, then it is.  If a memory allocation
		** is required to store the string, then value of pMem is unchanged.  In
		** either case, SQLITE_TOOBIG is returned.
		*/

		private static int sqlite3VdbeMemSetBlob(
		Mem pMem,           /* Memory cell to set to string value */
		byte[] zBlob,       /* Blob pointer */
		int n,              /* Bytes in Blob */
		u8 enc,             /* 0 for BLOBs */
		dxDel xDel          /* Destructor function */
		)
		{
			return sqlite3VdbeMemSetBlob(pMem, zBlob, 0, n >= 0 ? n : zBlob.Length, enc, xDel);
		} // Call w/o offset
Exemple #54
0
 static void sqlite3MemFreeMem(ref Mem pPrior)
 {
     pPrior = null;
 }
Exemple #55
0
		private static int sqlite3VdbeMemSetStr(
		Mem pMem,           /* Memory cell to set to string value */
		string z,           /* String pointer */
		int n,              /* Bytes in string, or negative */
		u8 enc,             /* Encoding of z.  0 for BLOBs */
		dxDel xDel          /* Destructor function */
		)
		{
			return sqlite3VdbeMemSetStr(pMem, z, 0, n, enc, xDel);
		} // Call w/o offset
    protected void Write(object value)
    {
        if (value is byte[] ba)
        {
            Mem.WriteByteRange(CurrentAddressValue, ba.ToList());
            CurrentAddressValue += ba.Length;
        }
        else if (value is Array a)
        {
            foreach (var item in a)
            {
                Write(item);
            }
        }
        else if (value.GetType().IsEnum)
        {
            var t = Enum.GetUnderlyingType(value.GetType());
            Write(Convert.ChangeType(value, t));
        }
        else if (value is bool bo)
        {
            Mem.WriteByte(CurrentAddressValue, (byte)(bo ? 1 : 0));
            CurrentAddressValue += sizeof(byte);
        }
        else if (value is sbyte sb)
        {
            Mem.WriteS8(CurrentAddressValue, sb);
            CurrentAddressValue += sizeof(sbyte);
        }
        else if (value is byte by)
        {
            Mem.WriteByte(CurrentAddressValue, by);
            CurrentAddressValue += sizeof(byte);
        }
        else if (value is short sh)
        {
            Mem.WriteS16(CurrentAddressValue, sh);
            CurrentAddressValue += sizeof(short);
        }
        else if (value is ushort ush)
        {
            Mem.WriteU16(CurrentAddressValue, ush);
            CurrentAddressValue += sizeof(ushort);
        }
        else if (value is int i32)
        {
            Mem.WriteS32(CurrentAddressValue, i32);
            CurrentAddressValue += sizeof(int);
        }
        else if (value is uint ui32)
        {
            Mem.WriteU32(CurrentAddressValue, ui32);
            CurrentAddressValue += sizeof(uint);
        }
        //else if (value is long lo)
        //{
        //    CurrentAddressValue += sizeof(long);
        //}
        //else if (value is ulong ulo)
        //{
        //    CurrentAddressValue += sizeof(ulong);
        //}
        //else if (value is float fl)
        //{
        //    CurrentAddressValue += sizeof(float);
        //}
        //else if (value is double dou)
        //{
        //    CurrentAddressValue += sizeof(double);
        //}
        //else if (value is string s)
        //{

        //}
        else
        {
            throw new NotSupportedException($"The specified type {value.GetType().Name} is not supported.");
        }
    }
Exemple #57
0
 /*
 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
 ** assumes the memory subsystem has already been initialized.
 */
 static Mem sqlite3Malloc( Mem pMem )
 {
   return sqlite3GlobalConfig.m.xMallocMem( pMem );
 }
 public void Dispose()
 {
     Mem.Del <Transform>(ref this._transform);
     Mem.Del <UITexture>(ref this._uiTexture);
     Mem.Del <MoveWith>(ref this._clsMoveWith);
 }
Exemple #59
0
 /*
 ** Allocate and zero memory.  If the allocation fails, make
 ** the mallocFailed flag in the connection pointer.
 */
 static Mem sqlite3DbMallocZero( sqlite3 db, Mem m )
 {
   return new Mem();
 }
Exemple #60
0
 private void OnDestroy()
 {
     if (mTexture_SecurityShip != null && mTexture_SecurityShip.mainTexture != null)
     {
         mTexture_SecurityShip = null;
     }
     if (mDifficulty != null)
     {
         mDifficulty = null;
     }
     if (mtouchEventArea != null)
     {
     }
     if (mMedalist != null)
     {
         mMedalist = null;
     }
     if (mboardud1 != null)
     {
         mboardud1 = null;
     }
     if (mWindowParam != null)
     {
         mWindowParam = null;
     }
     if (mShipTexture != null)
     {
         mShipTexture = null;
     }
     if (mbgWalls != null)
     {
         Mem.DelAry(ref mbgWalls);
     }
     if (mLabels != null)
     {
         Mem.DelAry(ref mLabels);
     }
     if (Medals != null)
     {
         Medals = null;
     }
     _now_page     = 0;
     _dbg_class    = 0;
     _Xpressed     = false;
     _firstUpdate  = false;
     needAnimation = false;
     _isTouch      = false;
     _isScene      = false;
     needUpdate    = false;
     if (_ANIM_filebase != null)
     {
         _ANIM_filebase = null;
     }
     if (mSecurityShipModel != null)
     {
         mSecurityShipModel = null;
     }
     if (_clsRecord != null)
     {
         _clsRecord = null;
     }
     if (label != null)
     {
         label = null;
     }
     if (label2 != null)
     {
         label2 = null;
     }
     if (sprite != null)
     {
         sprite = null;
     }
     if (mTexture_SecurityShip != null)
     {
         mTexture_SecurityShip = null;
     }
     if (texture != null)
     {
         texture = null;
     }
     if (_Button_L != null)
     {
         _Button_L = null;
     }
     if (_Button_R != null)
     {
         _Button_R = null;
     }
     if (_Button_L_B != null)
     {
         _Button_L_B = null;
     }
     if (_Button_R_B != null)
     {
         _Button_R_B = null;
     }
     if ((Object)_AM != null)
     {
         _AM = null;
     }
     if ((Object)_AM_l != null)
     {
         _AM_l = null;
     }
     if ((Object)_AM_b != null)
     {
         _AM_b = null;
     }
     if (_SM != null)
     {
         _SM = null;
     }
     if (ItemSelectController != null)
     {
         ItemSelectController = null;
     }
     if (_AS != null)
     {
         _AS = null;
     }
     if (_board1 != null)
     {
         _board1 = null;
     }
     alphaZero_b         = Color.black * 0f;
     __USEITEM_DOCKKEY__ = 0;
     if (_diff1 != null)
     {
         _diff1 = null;
     }
     if (_diff2 != null)
     {
         _diff2 = null;
     }
     _gotMedal       = false;
     _SelectableDiff = 0;
 }