/// <summary> /// Initializes a VirtualStream instance with a memory buffer size, memory flag and underlying stream /// specified. /// </summary> /// <param name="bufferSize">Memory buffer size</param> /// <param name="flag">Memory flag</param> /// <param name="dataStream">Underlying stream</param> private VirtualStream(int bufferSize, MemoryFlag flag, Stream dataStream) { if (null == dataStream) throw new ArgumentNullException("dataStream"); isInMemory = (flag != MemoryFlag.OnlyToDisk); memoryStatus = flag; bufferSize = Math.Min(bufferSize, MemoryThreshold); thresholdSize = bufferSize; if (isInMemory) wrappedStream = dataStream; // Don't want to double wrap memory stream else wrappedStream = new BufferedStream(dataStream, bufferSize); isDisposed = false; }
public static MemoryBuffer CreateBuffer( CLAPI instance, object[] data, Type t, MemoryFlag flags, object handleIdentifier) { MemoryBuffer mb = instance.context.CreateBuffer( flags | MemoryFlag.CopyHostPointer, t, data, handleIdentifier ); return(mb); }
public static extern IntPtr CreateImage2D( [In] IntPtr context, [In][MarshalAs(UnmanagedType.U8)] MemoryFlag flags, [In] IntPtr imageFormat, [In] UIntPtr imageWidth, [In] UIntPtr imageHeight, [In] UIntPtr imageRowPitch, [In] IntPtr hostPointer, [Out][MarshalAs(UnmanagedType.I4)] out Result errorCode);
/// <summary> /// Creates a buffer with the content of an image and the specified Memory Flags /// </summary> /// <param name="bmp">The image that holds the data</param> /// <param name="flags">The memory flags for the buffer creation</param> /// <returns></returns> public static MemoryBuffer CreateFromImage(Bitmap bmp, MemoryFlag flags) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte[] buffer = new byte[bmp.Width * bmp.Height * 4]; Marshal.Copy(data.Scan0, buffer, 0, buffer.Length); bmp.UnlockBits(data); #if NO_CL Logger.Log("Creating CL Buffer from Image", DebugChannel.Warning); return(null); #else MemoryBuffer mb = CreateBuffer(buffer, flags); return(mb); #endif }
/// <summary> /// Creates a buffer with the content of an image and the specified Memory Flags /// </summary> /// <param name="instance">CLAPI Instance for the current thread</param> /// <param name="bmp">The image that holds the data</param> /// <param name="flags">The memory flags for the buffer creation</param> /// <returns></returns> public static MemoryBuffer CreateFromImage( CLAPI instance, Bitmap bmp, MemoryFlag flags, object handleIdentifier) { BitmapData data = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb ); byte[] buffer = new byte[bmp.Width * bmp.Height * 4]; Marshal.Copy(data.Scan0, buffer, 0, buffer.Length); bmp.UnlockBits(data); ARGBtoBGRA(buffer); MemoryBuffer mb = CreateBuffer(instance, buffer, flags, handleIdentifier); return(mb); }
public override FLBuffer GetBuffer() { MemoryFlag flag = Modifiers.IsReadOnly ? MemoryFlag.ReadOnly : MemoryFlag.ReadWrite; if (!IsArray) { return(new LazyLoadingFLBuffer( root => new FLBuffer( CLAPI.CreateEmpty <byte>( root.Instance, root.InputSize, flag, "EmptySerializableBuffer." + Name ), root.Dimensions.x, root.Dimensions.y, root.Dimensions.z ), Modifiers.InitializeOnStart )); } return(new LazyLoadingFLBuffer( root => new FLBuffer( CLAPI.CreateEmpty <byte>( root.Instance, Size, flag, "EmptySerializableBuffer." + Name ), Size, 1, 1 ), Modifiers.InitializeOnStart )); }
public LazyFromFileFLBuffer(string file, bool isArray, int size, FLBufferModifiers modifiers) : base( null, modifiers .InitializeOnStart ) { File = file; MemoryFlag flag = modifiers.IsReadOnly ? MemoryFlag.ReadOnly : MemoryFlag.ReadWrite; if (isArray) { Loader = root => { Bitmap bmp = new Bitmap(Image.FromStream(IOManager.GetStream(File))); FLBuffer buf = new FLBuffer(root.Instance, bmp, DefinedBufferName + ":" + File, flag); bmp.Dispose(); return(buf); }; } else { Loader = root => { if (File == "INPUT") { return(root.Input); } Bitmap bmp = new Bitmap( Image.FromStream(IOManager.GetStream(File)), root.Dimensions.x, root.Dimensions.y ); FLBuffer buf = new FLBuffer(root.Instance, bmp, DefinedBufferName + ":" + File, flag); bmp.Dispose(); return(buf); }; } }
/// <summary> /// Initializes a VirtualStream instance with a memory buffer size, memory flag and underlying stream /// specified. /// </summary> /// <param name="bufferSize">Memory buffer size</param> /// <param name="flag">Memory flag</param> /// <param name="dataStream">Underlying stream</param> private VirtualStream(int bufferSize, MemoryFlag flag, Stream dataStream) { if (null == dataStream) { throw new ArgumentNullException("dataStream"); } isInMemory = (flag != MemoryFlag.OnlyToDisk); memoryStatus = flag; bufferSize = Math.Min(bufferSize, MemoryThreshold); thresholdSize = bufferSize; if (isInMemory) { wrappedStream = dataStream; // Don't want to double wrap memory stream } else { wrappedStream = new BufferedStream(dataStream, bufferSize); } isDisposed = false; }
public override FLBuffer GetBuffer() { MemoryFlag flag = Modifiers.IsReadOnly ? MemoryFlag.ReadOnly : MemoryFlag.ReadWrite; if (IsArray) { return(new LazyLoadingFLBuffer( root => { FLBuffer buf = new FLBuffer( root.Instance, Bitmap, "BitmapBuffer." + Name, flag ); return buf; }, Modifiers.InitializeOnStart )); } return(new LazyLoadingFLBuffer( root => { Bitmap bmp = new Bitmap(Bitmap, root.Dimensions.x, root.Dimensions.y); FLBuffer buf = new FLBuffer( root.Instance, bmp, "BitmapBuffer." + Name, flag ); bmp.Dispose(); return buf; }, Modifiers.InitializeOnStart )); }
public WrappedMemoryPool(MemoryPool <byte> memoryPool, MemoryFlag flag) { this.flag = flag; this.memoryPool = memoryPool; }
public VirtualStream(MemoryFlag flag, bool forAsync = false) : this(ThresholdMax, flag, flag == MemoryFlag.OnlyToDisk ? CreatePersistentStream(forAsync) : new MemoryStream(), forAsync) { }
public MemoryAllocation CreateMemoryAllocation(IntPtr clContext, uint byteSize, MemoryFlag flags, IntPtr data) { Result err; var buffer = MemoryNativeApi.CreateBuffer(clContext, flags, new UIntPtr(byteSize), data, out err); if (err != Result.Success) { OnLowDeviceMemory(); buffer = MemoryNativeApi.CreateBuffer(clContext, flags, new UIntPtr(byteSize), data, out err); if (err != Result.Success) { ThrowOnError(err, String.Format("Failed to allocate device memory. Size: {0}", byteSize)); } } return(new MemoryAllocation(buffer, byteSize, flags)); }
public WrappedMemory(IMemoryOwner <byte> memoryOwner, MemoryFlag flag) : this(flag) { this.memoryOwner = memoryOwner; }
/// <summary> /// Define handler that loads defined Textures /// </summary> /// <param name="instance">CLAPI Instance of the Current Thread</param> /// <param name="arg">Args from the FL Script</param> /// <param name="defines">Defines</param> /// <param name="width">width of the input buffer</param> /// <param name="height">height of the input buffer</param> /// <param name="depth">depth of the input buffer</param> /// <param name="channelCount">channel count of the input buffer</param> /// <param name="kernelDb">the kernel database to use</param> private void DefineTexture(CLAPI instance, string[] arg, Dictionary <string, CLBufferInfo> defines, int width, int height, int depth, int channelCount, KernelDatabase kernelDb) { if (arg.Length < 2) { throw new FLInvalidFunctionUseException(SCRIPT_DEFINE_KEY, "Invalid Define statement"); } string varname = arg[0].Trim(); if (defines.ContainsKey(varname)) { Logger.Log(DebugChannel.Error, Verbosity.Level1, "Overwriting " + varname, DebugChannel.Warning | DebugChannel.OpenFL, 10); defines.Remove(varname); } MemoryFlag flags = MemoryFlag.ReadWrite; string[] flagTest = varname.Split(' '); if (flagTest.Length > 1) { varname = flagTest[1]; if (flagTest[0] == "r") { flags = MemoryFlag.ReadOnly; } else if (flagTest[0] == "w") { flags = MemoryFlag.WriteOnly; } } string[] args = arg[1].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string filename = args[0].Trim(); byte[] activeChannels = new byte[channelCount]; for (int i = 0; i < activeChannels.Length; i++) { activeChannels[i] = 1; } int inputBufferSize = width * height * depth * channelCount; if (IsSurroundedBy(filename, FILEPATH_INDICATOR)) { string fn = filename.Replace(FILEPATH_INDICATOR, ""); if (File.Exists(fn)) { Bitmap bmp = new Bitmap((Bitmap)System.Drawing.Image.FromFile(fn), width, height); CLBufferInfo info = new CLBufferInfo(CLAPI.CreateFromImage(instance, bmp, MemoryFlag.CopyHostPointer | flags), true); info.SetKey(varname); defines.Add(varname, info); } else { throw new FLInvalidFunctionUseException(DEFINE_KEY, "Invalid Filepath", new InvalidFilePathException(fn)); } } else if (filename == "rnd") { MemoryBuffer buf = CLAPI.CreateEmpty <byte>(instance, inputBufferSize, flags | MemoryFlag.CopyHostPointer); CLAPI.WriteRandom(instance, buf, Randombytesource, activeChannels, false); CLBufferInfo info = new CLBufferInfo(buf, true); info.SetKey(varname); defines.Add(varname, info); } else if (filename == "urnd") { MemoryBuffer buf = CLAPI.CreateEmpty <byte>(instance, inputBufferSize, flags | MemoryFlag.CopyHostPointer); CLAPI.WriteRandom(instance, buf, Randombytesource, activeChannels, true); CLBufferInfo info = new CLBufferInfo(buf, true); info.SetKey(varname); defines.Add(varname, info); } else if (filename == "empty") { CLBufferInfo info = new CLBufferInfo(CLAPI.CreateEmpty <byte>(instance, inputBufferSize, flags), true); info.SetKey(varname); defines.Add(varname, info); } else if (filename == "wfc" || filename == "wfcf") { bool force = filename == "wfcf"; if (args.Length < 10) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!int.TryParse(args[2], out int n)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!int.TryParse(args[3], out int widh)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!int.TryParse(args[4], out int heigt)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!bool.TryParse(args[5], out bool periodicInput)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!bool.TryParse(args[6], out bool periodicOutput)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!int.TryParse(args[7], out int symmetry)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!int.TryParse(args[8], out int ground)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else if (!int.TryParse(args[9], out int limit)) { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Define statement"); } else { string fn = args[1].Trim().Replace(FILEPATH_INDICATOR, ""); if (CLAPI.FileExists(fn)) { Bitmap bmp; WFCOverlayMode wfc = new WFCOverlayMode(fn, n, widh, heigt, periodicInput, periodicOutput, symmetry, ground); if (force) { do { wfc.Run(limit); bmp = new Bitmap(wfc.Graphics(), new Size(width, height)); //Apply scaling } while (!wfc.Success); } else { wfc.Run(limit); bmp = new Bitmap(wfc.Graphics(), new Size(width, height)); //Apply scaling } CLBufferInfo info = new CLBufferInfo(CLAPI.CreateFromImage(instance, bmp, MemoryFlag.CopyHostPointer | flags), true); info.SetKey(varname); defines.Add(varname, info); } else { throw new FLInvalidFunctionUseException("wfc", "Invalid WFC Image statement", new InvalidFilePathException(fn)); } } } else { StringBuilder s = new StringBuilder(); foreach (string s1 in args) { s.Append(s1 + " "); } throw new FLInvalidFunctionUseException(DEFINE_KEY, "Define statement wrong: " + s); } }
/// <summary> /// Initializes a VirtualStream instance with a default memory size and memory flag specified. /// </summary> /// <param name="flag">Memory flag</param> public VirtualStream(MemoryFlag flag) : this(DefaultMemorySize, flag, (flag == MemoryFlag.OnlyToDisk) ? CreatePersistentStream() : new MemoryStream()) { }
/// <summary> /// Creates an empty buffer of type T with the specified size and MemoryFlags /// </summary> /// <typeparam name="T">The type of the struct</typeparam> /// <param name="size">The size of the buffer(Total size in bytes: size*sizeof(T)</param> /// <param name="flags">The memory flags for the buffer creation</param> /// <returns></returns> public static MemoryBuffer CreateEmpty <T>(int size, MemoryFlag flags) where T : struct { T[] arr = new T[size]; return(CreateBuffer(arr, flags)); }
/// <summary> /// Creates a Buffer with the specified content and Memory Flags /// </summary> /// <typeparam name="T">Type of the struct</typeparam> /// <param name="instance">CLAPI Instance for the current thread</param> /// <param name="data">The array of T</param> /// <param name="flags">The memory flags for the buffer creation</param> /// <returns></returns> public static MemoryBuffer CreateBuffer <T>(CLAPI instance, T[] data, MemoryFlag flags, object handleIdentifier) where T : struct { object[] arr = Array.ConvertAll(data, x => (object)x); return(CreateBuffer(instance, arr, typeof(T), flags, handleIdentifier)); }
public static MemoryBuffer CreateBuffer <T>(T[] data, MemoryFlag flags) { return(GetInstance().createBuffer <T>(data, flags)); }
public static MemoryBuffer CreateBuffer(object[] data, Type t, MemoryFlag flags) { MemoryBuffer mb = GetInstance().c.CreateBuffer(flags, t, data); return(mb); }
public static MemoryBuffer CreateEmpty <T>(int size, MemoryFlag flags) where T : struct { T[] t = new T[size]; return(CreateBuffer <T>(t, flags | MemoryFlag.CopyHostPointer)); }
public static MemoryBuffer CreateRandomByte(int size, byte[] channelEnableState, MemoryFlag flags) { byte[] buffer = CreateRandom(size, channelEnableState); MemoryBuffer mb = GetInstance().c.CreateBuffer(flags | MemoryFlag.CopyHostPointer, buffer); return(mb); }
/// <summary> /// Initializes a VirtualStream instance with a memory buffer size and memory flag specified. /// </summary> /// <param name="bufferSize">Memory buffer size</param> /// <param name="flag">Memory flag</param> public VirtualStream(int bufferSize, MemoryFlag flag) : this(bufferSize, flag, (flag == MemoryFlag.OnlyToDisk) ? CreatePersistentStream() : new MemoryStream(bufferSize)) { }
/// <summary> /// Creates an empty buffer of type T with the specified size and MemoryFlags /// </summary> /// <typeparam name="T">The type of the struct</typeparam> /// <param name="instance">CLAPI Instance for the current thread</param> /// <param name="size">The size of the buffer(Total size in bytes: size*sizeof(T)</param> /// <param name="flags">The memory flags for the buffer creation</param> /// <returns></returns> public static MemoryBuffer CreateEmpty <T>(CLAPI instance, int size, MemoryFlag flags, object handleIdentifier) where T : struct { return(CreateEmptyOptimized <T>(instance, size, flags, handleIdentifier)); }
public override FLBuffer GetBuffer() { MemoryFlag flag = Modifiers.IsReadOnly ? MemoryFlag.ReadOnly : MemoryFlag.ReadWrite; return(new FLBuffer(CLAPI.MainThread, Data, Width, Height, Depth, "BinaryBuffer." + Name, flag)); }
public WrappedMemory(MemoryFlag flag) { this.Flag = flag; }
/// <summary> /// Creates a Buffer with the specified content and Memory Flags /// </summary> /// <typeparam name="T">Type of the struct</typeparam> /// <param name="data">The array of T</param> /// <param name="flags">The memory flags for the buffer creation</param> /// <returns></returns> public static MemoryBuffer CreateBuffer <T>(T[] data, MemoryFlag flags) where T : struct { object[] arr = Array.ConvertAll(data, x => (object)x); return(CreateBuffer(arr, typeof(T), flags)); }
void ParseDefines() { for (int i = source.Count - 1; i >= 0; i--) { if (source[i].StartsWith(defineKey)) { string[] kvp = source[i].Remove(0, defineKey.Length).Split(':'); if (kvp.Length < 2) { throw new Exception("Invalid Define statement at line " + i); } string varname = kvp[0].Trim(); if (defines.ContainsKey(varname)) { this.Log("Overwriting " + varname, DebugChannel.Warning, 10); defines.Remove(varname); } MemoryFlag flags = MemoryFlag.ReadWrite; string[] flagTest = varname.Split(' '); if (flagTest.Length > 1) { varname = flagTest[1]; if (flagTest[0] == "r") { flags = MemoryFlag.ReadOnly; } else if (flagTest[0] == "w") { flags = MemoryFlag.WriteOnly; } } string[] args = kvp[1].Split(' ', StringSplitOptions.RemoveEmptyEntries); string filename = args[0].Trim(); if (IsSurroundedBy(filename, "\"")) { defines.Add(varname, CLFilterAPI.CreateFromImage((Bitmap)Image.FromFile(filename.Replace("\"", "")), MemoryFlag.CopyHostPointer | flags)); } else if (filename == "random") { defines.Add(varname, CLFilterAPI.CreateRandomByte(size, channelEnableStates, MemoryFlag.CopyHostPointer | flags)); } else if (filename == "empty") { defines.Add(varname, CLFilterAPI.CreateEmpty <byte>(size, MemoryFlag.CopyHostPointer | flags)); } else if (filename == "wfc") { if (args.Length < 10) { throw new Exception("Invalid Define statement at line " + i); } if (!int.TryParse(args[2], out int n)) { throw new Exception("Invalid N argument"); } if (!int.TryParse(args[3], out int width)) { throw new Exception("Invalid width argument"); } if (!int.TryParse(args[4], out int height)) { throw new Exception("Invalid height argument"); } if (!bool.TryParse(args[5], out bool periodicInput)) { throw new Exception("Invalid periodicInput argument"); } if (!bool.TryParse(args[6], out bool periodicOutput)) { throw new Exception("Invalid periodicOutput argument"); } if (!int.TryParse(args[7], out int symetry)) { throw new Exception("Invalid symetry argument"); } if (!int.TryParse(args[8], out int ground)) { throw new Exception("Invalid ground argument"); } if (!int.TryParse(args[9], out int limit)) { throw new Exception("Invalid limit argument"); } WaveFunctionCollapse wfc = new WFCOverlayMode(args[1].Trim().Replace("\"", ""), n, width, height, periodicInput, periodicOutput, symetry, ground); wfc.Run(limit); Bitmap bmp = new Bitmap(wfc.Graphics(), new Size(this.width, this.height)); //Apply scaling defines.Add(varname, CLFilterAPI.CreateFromImage(bmp, MemoryFlag.CopyHostPointer | flags)); } else { throw new InvalidOperationException("Can not resolve symbol: " + varname + " in line " + i); } } } }
//Optimization private static MemoryBuffer CreateEmptyOptimized <T>(CLAPI instance, int size, MemoryFlag flags, object handleIdentifier) where T : struct { //return CreateBuffer(instance, new byte[size], flags, handleIdentifier); int bufByteSize = Marshal.SizeOf <T>() * size; return(instance.context.CreateBuffer(flags | MemoryFlag.AllocateHostPointer, bufByteSize, handleIdentifier)); }