예제 #1
0
        public static void Main(string[] args)
        {
            // Create algorithm setup.
            var algorithmZoom1       = new RuntimeLayer(new AlgorithmZoom2D());
            var algorithmZoom2       = new RuntimeLayer(new AlgorithmZoom2D());
            var algorithmZoom3       = new RuntimeLayer(new AlgorithmZoom2D());
            var algorithmZoom4       = new RuntimeLayer(new AlgorithmZoom2D());
            var algorithmInitialLand = new RuntimeLayer(new AlgorithmInitialBool());

            algorithmZoom4.SetInput(0, algorithmInitialLand);
            algorithmZoom3.SetInput(0, algorithmZoom4);
            algorithmZoom2.SetInput(0, algorithmZoom3);
            algorithmZoom1.SetInput(0, algorithmZoom2);

            StorageLayer[] storage = null;
            Console.WriteLine("Storing...");
            using (var writer = new StreamWriter("WorldConfig.xml", false))
                StorageAccess.SaveStorage(
                    new StorageLayer[] { StorageAccess.FromRuntime(algorithmZoom1) }, writer);

            Console.WriteLine("Loading...");
            using (var reader = new StreamReader("WorldConfig.xml"))
                storage = StorageAccess.LoadStorage(reader);
            foreach (var l in storage)
            {
                Console.WriteLine(l.Algorithm.GetType().FullName);
            }
        }
예제 #2
0
        public ActionResult Download(string reportId)
        {
            var owinContext  = this.HttpContext.GetOwinContext();
            var user         = owinContext.GetUser();
            var tenantId     = user.GetTenantId();
            var userObjectId = user.GetUserObjectId();

            var telemetryContext = new TelemetryContext
            {
                TenantId     = tenantId,
                UserObjectId = userObjectId
            };

            TelemetryHelper.LogVerbose(
                @"ReportController::Download",
                telemetryContext);

            var fileName = DataAccess.GetReportFileName(tenantId, userObjectId, reportId);

            TelemetryHelper.LogInformation(
                FormattableString.Invariant($"Got report file name {fileName} for report {reportId}."),
                telemetryContext);

            var stream = new MemoryStream();

            StorageAccess.DownloadFile(fileName, stream);
            stream.Position = 0;

            TelemetryHelper.LogInformation(
                FormattableString.Invariant($"Got file stream with size {stream.Length} for report {reportId}"),
                telemetryContext);

            return(this.File(stream, @"application/html", $"{fileName}"));
        }
예제 #3
0
        /// <summary>
        /// Retrieves an interface to the device's property store.
        /// </summary>
        /// <param name="storageAccess">The storage-access mode. This parameter specifies whether to open the property store in read mode, write mode, or read/write mode.</param>
        /// <returns><see cref="PropertyStore"/> for the <see cref="MMDevice"/>.</returns>
        public PropertyStore OpenPropertyStore(StorageAccess storageAccess)
        {
            IntPtr propstorePtr;

            CoreAudioAPIException.Try(OpenPropertyStoreNative(storageAccess, out propstorePtr),
                                      "IMMDevice", "OpenPropertyStore");
            return(new PropertyStore(propstorePtr));
        }
예제 #4
0
파일: MMDevice.cs 프로젝트: yazici/AudioLab
 public unsafe int OpenPropertyStoreNative(StorageAccess access, out IntPtr propertyStore)
 {
     propertyStore = IntPtr.Zero;
     fixed(void *pps = &propertyStore)
     {
         return(InteropCalls.CallI(_basePtr, unchecked (access), pps, ((void **)(*(void **)_basePtr))[4]));
     }
 }
예제 #5
0
 /// <summary>
 /// Retrieves an interface to the device's property store.
 /// </summary>
 /// <param name="storageAccess">The storage-access mode. This parameter specifies whether to open the property store in read mode, write mode, or read/write mode.</param>
 /// <param name="propertyStore">A pointer variable into which the method writes the address of the IPropertyStore interface of the device's property store.</param>
 /// <returns>HRESULT</returns>
 public unsafe int OpenPropertyStoreNative(StorageAccess storageAccess, out IntPtr propertyStore)
 {
     propertyStore = IntPtr.Zero;
     fixed(void *pps = &propertyStore)
     {
         return(LocalInterop.Calli(UnsafeBasePtr, unchecked (storageAccess), pps,
                                   ((void **)(*(void **)UnsafeBasePtr))[4]));
     }
 }
예제 #6
0
        public ExportForm(FlowElement flowElement)
        {
            InitializeComponent();

            this.m_Layer           = StorageAccess.ToRuntime((flowElement as AlgorithmFlowElement).Layer);
            this.m_Bitmap          = new Bitmap(1024 + 32, 1024 + 256);
            this.c_RenderBox.Image = this.m_Bitmap;
            this.c_Timer.Start();
        }
        public static Bitmap RegenerateImageForLayer(StorageLayer layer, long ox, long oy, long oz, int width, int height, int depth, bool compiled = false)
        {
            var runtime = StorageAccess.ToRuntime(layer);

            //if (compiled)
            //    return Regenerate3DImageForLayer(runtime, ox, oy, oz, width, height, depth, StorageAccess.ToCompiled(layer));
            //else
            return(Regenerate3DImageForLayer(runtime, ox, oy, oz, width, height, depth));
        }
예제 #8
0
        public AnalyseForm(FlowElement flowElement)
        {
            InitializeComponent();

            this.m_Layer = StorageAccess.ToRuntime((flowElement as AlgorithmFlowElement).Layer);
            this.c_AnalysisAddOptionsMenu.Items.AddRange((
                                                             from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                                             from type in assembly.GetTypes()
                                                             where typeof(AnalysisEngine).IsAssignableFrom(type) && !type.IsGenericType && !type.IsAbstract
                                                             select new TypeWrapper(type)).ToArray());
        }
예제 #9
0
        private void c_LoadConfigurationButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Filter          = "XML Files|*.xml",
                CheckFileExists = true,
                CheckPathExists = true
            };

            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StorageLayer[] layers;
                try
                {
                    // Load from file.
                    using (var stream = new StreamReader(openFileDialog.FileName))
                        layers = StorageAccess.LoadStorage(stream);
                    if (layers == null)
                    {
                        MessageBox.Show(this, "Unable to load configuration file.", "Configuration invalid.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Unable to load configuration file.", "Configuration invalid.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // Reset state.
                this.c_FlowInterfaceControl.Elements.Clear();
                this.c_FlowInterfaceControl.Invalidate();
                this.m_LastSavePath = openFileDialog.FileName;
                this.c_SaveConfigurationButton.Enabled = true;

                // Create algorithm flow elements.
                this.c_FlowInterfaceControl.Elements.AddRange(
                    layers.Where(v => v != null)
                    .Select(v => new AlgorithmFlowElement(this.c_FlowInterfaceControl, v)
                {
                    X = v.EditorX, Y = v.EditorY
                })
                    );

                /*foreach (var el in layers)
                 * {
                 *  el.SetDeserializationData(this.c_FlowInterfaceControl);
                 *  this.c_FlowInterfaceControl.Elements.Add(el);
                 * }
                 * foreach (FlowElement el in config)
                 *  this.c_FlowInterfaceControl.PushForReprocessing(el);
                 * this.c_FlowInterfaceControl.Invalidate();*/
            }
        }
예제 #10
0
 public TraceForm(FlowElement flowElement)
 {
     InitializeComponent();
     this.m_Layer = StorageAccess.ToRuntime((flowElement as AlgorithmFlowElement).Layer);
     this.c_FormZoomSize.Items.Add(new ZoomLevel {
         Level = 1
     });
     this.c_FormZoomSize.Items.Add(new ZoomLevel {
         Level = 2
     });
     this.c_FormZoomSize.SelectedIndex = 0;
 }
예제 #11
0
 static ChunkProvider()
 {
     // Use StorageAccess to load reference to world generation.
     StorageLayer[] layers;
     using (var reader = new StreamReader(WORLD_CONFIG_FILE))
         layers = StorageAccess.LoadStorage(reader);
     foreach (var layer in layers)
     {
         if (layer.Algorithm is AlgorithmResult)
         {
             if ((layer.Algorithm as AlgorithmResult).DefaultForGame)
             {
                 m_ResultLayer = StorageAccess.ToRuntime(layer);
                 break;
             }
         }
     }
 }
예제 #12
0
 private static RuntimeLayer CreateLayerFromConfig(string path, GenerationRequest request)
 {
     // Use StorageAccess to load reference to world generation.
     StorageLayer[] layers;
     using (var reader = new StreamReader(path))
         layers = StorageAccess.LoadStorage(reader);
     foreach (var layer in layers)
     {
         if ((layer.Algorithm is AlgorithmResult) &&
             (layer.Algorithm as AlgorithmResult).Name == request.LayerName &&
             ((layer.Algorithm as AlgorithmResult).ShowInMakeMeAWorld ||
              (layer.Algorithm as AlgorithmResult).PermitInMakeMeAWorld))
         {
             return(StorageAccess.ToRuntime(layer));
         }
     }
     return(null);
 }
예제 #13
0
        private void c_SaveConfigurationButton_Click(object sender, EventArgs e)
        {
            if (this.m_LastSavePath == null)
            {
                this.c_SaveConfigurationAsButton.PerformClick();
            }
            else
            {
                // Convert to storage layers.
                var layers = new List <StorageLayer>();
                foreach (var element in this.c_FlowInterfaceControl.Elements)
                {
                    var algorithmElement = element as AlgorithmFlowElement;
                    if (algorithmElement == null)
                    {
                        continue;
                    }

                    algorithmElement.Layer.EditorX = element.X;
                    algorithmElement.Layer.EditorY = element.Y;

                    layers.Add(algorithmElement.Layer);
                }

                // Save the layers.
                try
                {
                    var memory = new MemoryStream();
                    using (var writer = new StreamWriter(memory))
                    {
                        StorageAccess.SaveStorage(layers.ToArray(), writer);
                        memory.Seek(0, SeekOrigin.Begin);
                        using (var file = new StreamWriter(this.m_LastSavePath, false))
                            memory.CopyTo(file.BaseStream);
                    }

                    MessageBox.Show(this, "Save successful.", "Configuration saved.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Save failure.", ex.Message + "\r\n" + ex.StackTrace, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #14
0
        private static string GetDefaultAvailableLayer(string path)
        {
            // Use StorageAccess to load reference to world generation.
            StorageLayer[] layers;
            using (var reader = new StreamReader(path))
                layers = StorageAccess.LoadStorage(reader);
            foreach (var layer in layers)
            {
                if (layer.Algorithm is AlgorithmResult)
                {
                    if ((layer.Algorithm as AlgorithmResult).DefaultForMakeMeAWorld)
                    {
                        return((layer.Algorithm.Is2DOnly ? "2D," : "3D,") +
                               (layer.Algorithm as AlgorithmResult).Name);
                    }
                }
            }

            return(null);
        }
예제 #15
0
        private static List <string> GetListOfAvailableLayers(string path)
        {
            var result = new List <string>();

            // Use StorageAccess to load reference to world generation.
            StorageLayer[] layers;
            using (var reader = new StreamReader(path))
                layers = StorageAccess.LoadStorage(reader);
            foreach (var layer in layers)
            {
                if (layer.Algorithm is AlgorithmResult)
                {
                    if ((layer.Algorithm as AlgorithmResult).ShowInMakeMeAWorld)
                    {
                        result.Add(
                            (layer.Algorithm.Is2DOnly ? "2D," : "3D,") +
                            (layer.Algorithm as AlgorithmResult).Name);
                    }
                }
            }

            return(result);
        }
예제 #16
0
        public ActionResult Remove(int id)
        {
            var owinContext  = this.HttpContext.GetOwinContext();
            var user         = owinContext.GetUser();
            var tenantId     = user.GetTenantId();
            var userObjectId = user.GetUserObjectId();

            var telemetryContext = new TelemetryContext
            {
                TenantId     = tenantId,
                UserObjectId = userObjectId
            };

            TelemetryHelper.LogVerbose(@"ReportController::Remove", telemetryContext);

            // Remove the info of task and report in the database
            var fileName = DataAccess.TryRemoveAssessmentTaskById(id);

            // Report file exists in the blob
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                TelemetryHelper.LogInformation(
                    FormattableString.Invariant($"Remove report file with name {fileName}."),
                    telemetryContext);

                // Remove file saved in the blob
                StorageAccess.RemoveFile(fileName);
                TokenStore.Instance.RemoveTokenWrapperByTaskId(id);
            }

            TelemetryHelper.LogInformation(
                FormattableString.Invariant($"Report file with Id {id}, name {fileName} has been successfully removed."),
                telemetryContext);

            return(this.Redirect(this.Request.UrlReferrer.ToString()));
        }
예제 #17
0
        private static Bitmap RenderPartial3D(RuntimeLayer layer, int sx, int sy, int sz, int width, int height, int depth)
        {
            var bitmap   = new Bitmap(width * 2, height * 3);
            var graphics = Graphics.FromImage(bitmap);

            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
            int[] data;
            try
            {
                int computations;
                data = layer.GenerateData(TemporaryCrapBecauseIDidNotReallyDesignThingsVeryWell.X + sx, TemporaryCrapBecauseIDidNotReallyDesignThingsVeryWell.Y + sy, TemporaryCrapBecauseIDidNotReallyDesignThingsVeryWell.Z + sz, width, height, depth, out computations);

                var render  = GetCellRenderOrder(RenderToNE, width, height);
                var ztop    = layer.Algorithm.Is2DOnly ? 1 : depth;
                var zbottom = 0;
                for (var z = zbottom; z < ztop; z++)
                {
                    var rcx = width / 2 - 1 + 16;
                    var rcy = height / 2 - 15 + 32;
                    var rw  = 2;
                    var rh  = 1;
                    for (var i = 0; i < render.Length; i++)
                    {
                        // Calculate the X / Y of the tile in the grid.
                        var x = render[i] % width;
                        var y = render[i] / width;

                        // Calculate the render position on screen.
                        var rx = rcx + (int)((x - y) / 2.0 * rw);// (int)(x / ((RenderWidth + 1) / 2.0) * rw);
                        var ry = rcy + (x + y) * rh - (rh / 2 * (width + height)) - (z - zbottom) * 1;

                        while (true)
                        {
                            try
                            {
                                Color lc;
                                if (layer.GetInputs().Length > 0)
                                {
                                    lc = layer.Algorithm.GetColorForValue(
                                        StorageAccess.FromRuntime(layer.GetInputs()[0]),
                                        data[x + y * width + z * width * height]);
                                }
                                else
                                {
                                    lc = layer.Algorithm.GetColorForValue(
                                        null,
                                        data[x + y * width + z * width * height]);
                                }
                                var sb = new SolidBrush(Color.FromArgb(lc.A, lc.R, lc.G, lc.B));
                                graphics.FillRectangle(
                                    sb,
                                    new Rectangle(rx, ry, rw, rh)
                                    );
                                break;
                            }
                            catch (InvalidOperationException)
                            {
                                // Graphics can be in use elsewhere, but we don't care; just try again.
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return(bitmap);
        }
예제 #18
0
        private void PerformMeasurements()
        {
            // Settings.
            var iterations   = 1000;
            var warningLimit = 100000; // 0.1s
            var badLimit     = 300000; // 0.3s

            // Perform conversions.
            var        runtime  = StorageAccess.ToRuntime(this.m_Layer);
            IGenerator compiled = null;

            try
            {
                compiled = StorageAccess.ToCompiled(runtime);
            }
            catch (Exception)
            {
                // Failed to compile layer.
            }

            // First check how long it takes for the runtime layer to do 1000 operations of 8x8x8.
            var runtimeStart        = DateTime.Now;
            var runtimeComputations = 0;

            for (var i = 0; i < iterations; i++)
            {
                runtime.GenerateData(0, 0, 0, 8, 8, 8, out runtimeComputations);
            }
            var runtimeEnd = DateTime.Now;

            // Now check how long it takes the compiled layer to do 1000 operations of 8x8x8.
            var compiledStart        = DateTime.Now;
            var compiledComputations = 0;

            if (compiled != null)
            {
                try
                {
                    for (var i = 0; i < iterations; i++)
                    {
                        compiled.GenerateData(0, 0, 0, 8, 8, 8, out compiledComputations);
                    }
                }
                catch
                {
                    compiled = null;
                }
            }
            var compiledEnd = DateTime.Now;

            // Determine the per-operation cost.
            var runtimeCost  = runtimeEnd - runtimeStart;
            var compiledCost = compiledEnd - compiledStart;
            var runtimeus    = Math.Round((runtimeCost.TotalMilliseconds / iterations) * 1000, 0); // Microseconds.
            var compiledus   = Math.Round((compiledCost.TotalMilliseconds / iterations) * 1000, 0);

            // Define colors and determine values.
            var okay          = new SolidBrush(Color.LightGreen);
            var warning       = new SolidBrush(Color.Orange);
            var bad           = new SolidBrush(Color.IndianRed);
            var runtimeColor  = okay;
            var compiledColor = okay;

            if (runtimeus > warningLimit)
            {
                runtimeColor = warning;
            }
            if (compiledus > warningLimit)
            {
                compiledColor = warning;
            }
            if (runtimeus > badLimit)
            {
                runtimeColor = bad;
            }
            if (compiledus > badLimit)
            {
                compiledColor = bad;
            }

            // Draw performance measurements.
            Bitmap bitmap;

            if (runtimeComputations != compiledComputations && compiled != null)
            {
                bitmap = new Bitmap(128, 48);
            }
            else
            {
                bitmap = new Bitmap(128, 32);
            }
            var graphics = Graphics.FromImage(bitmap);
            var font     = new Font(SystemFonts.DefaultFont, FontStyle.Bold);

            graphics.Clear(Color.Black);
            if (runtimeComputations != compiledComputations && compiled != null)
            {
                graphics.DrawString("Computation mismatch!", font, bad, new PointF(0, 0));
                graphics.DrawString("Runtime:", font, runtimeColor, new PointF(0, 16));
                graphics.DrawString(runtimeComputations + "c", font, runtimeColor, new PointF(70, 16));
                if (compiled != null)
                {
                    graphics.DrawString("Compiled:", font, compiledColor, new PointF(0, 32));
                    graphics.DrawString(compiledComputations + "c", font, compiledColor, new PointF(70, 32));
                }
                else
                {
                    graphics.DrawString("Unable to compile.", font, bad, new PointF(0, 32));
                }
            }
            else
            {
                graphics.DrawString("Runtime:", font, runtimeColor, new PointF(0, 0));
                graphics.DrawString(runtimeus + "\xB5s", font, runtimeColor, new PointF(70, 0));
                if (compiled != null)
                {
                    graphics.DrawString("Compiled:", font, compiledColor, new PointF(0, 16));
                    graphics.DrawString(compiledus + "\xB5s", font, compiledColor, new PointF(70, 16));
                }
                else
                {
                    graphics.DrawString("Unable to compile.", font, bad, new PointF(0, 16));
                }
            }
            if (this.m_AdditionalInformation != null)
            {
                this.m_AdditionalInformation.Dispose();
            }
            this.m_AdditionalInformation = bitmap;

            // TEMPORARY: Use the compiled layer to re-render the output.
            if (compiled != null)
            {
                this.m_CompiledBitmap = AlgorithmFlowImageGeneration.RegenerateImageForLayer(this.m_Layer,
                                                                                             TemporaryCrapBecauseIDidNotReallyDesignThingsVeryWell.X,
                                                                                             TemporaryCrapBecauseIDidNotReallyDesignThingsVeryWell.Y,
                                                                                             TemporaryCrapBecauseIDidNotReallyDesignThingsVeryWell.Z,
                                                                                             64, 64, 64, true);
            }
        }
예제 #19
0
 internal static unsafe int Calli(void *_basePtr, StorageAccess storageAccess, void *pps, void *p)
 {
     throw new NotImplementedException();
 }
예제 #20
0
 internal static unsafe int CallI(void* _basePtr, StorageAccess storageAccess, void* pps, void* p)
 {
     throw new NotImplementedException();
 }
예제 #21
0
 public PropertyStore OpenPropertyStore(StorageAccess storageAccess)
 {
     IntPtr propstorePtr;
     CoreAudioAPIException.Try(OpenPropertyStoreNative(storageAccess, out propstorePtr),
         "IMMDevice", "OpenPropertyStore");
     return new PropertyStore(propstorePtr);
 }
        public HttpResponseMessage GetStorageAccessResponse(HttpRequestMessage req)
        {
            var storageConnectingString = CloudConfigurationManager.GetSetting("StorageAccount.ConnectionString");
            var storageAccount          = CloudStorageAccount.Parse(storageConnectingString);

            if (storageAccount == null)
            {
                return(_httpRequestMessageHelper.CreateBadRequestResponse(req, new
                {
                    error = "StorageAccount is null"
                }));
            }

            HttpResponseMessage responseMessage;

            try
            {
                if (!_httpRequestMessageHelper.IsValidContentType(req))
                {
                    return(_httpRequestMessageHelper.CreateBadRequestResponse(req, new
                    {
                        error = "Request has invalid content type"
                    }));
                }

                _log.Info("Started generating SAS token");

                if (_httpRequestMessageHelper.IsContentCompressed(req))
                {
                    req.Content = _httpRequestMessageHelper.DecompressHttpContent(req);
                }

                dynamic data = req.Content.ReadAsAsync <object>().Result;
                if (data.container == null)
                {
                    return(_httpRequestMessageHelper.CreateBadRequestResponse(req, new
                    {
                        error = "Specify value for 'container'"
                    }));
                }

                bool success = Enum.TryParse(data.permissions.ToString(), out SharedAccessBlobPermissions permissions);
                if (!success)
                {
                    return(_httpRequestMessageHelper.CreateBadRequestResponse(req, new
                    {
                        error = "Invalid value for 'permissions'"
                    }));
                }

                var blobClient = storageAccount.CreateCloudBlobClient();
                var container  = blobClient.GetContainerReference(data.container.ToString());

                var sasToken = data.blobName != null?
                               GetBlobSasToken(container, data.blobName.ToString(), permissions) :
                                   GetContainerSasToken(container, permissions);

                // Response:
                // token - SAS token, including a leading "?"
                // uri - Resource URI with token appended as query string
                var result = new StorageAccess
                {
                    Token = sasToken,
                    Uri   = data.blobName == null ? container.Uri + sasToken : container.Uri + "/" + data.blobName.ToString() + sasToken
                };

                responseMessage = _httpRequestMessageHelper.CreateOkResponse(req, result);

                _log.Info("Generating SAS token has ended");
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                responseMessage = req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }

            return(responseMessage);
        }
        public static Bitmap RenderTraceResult(
            RuntimeLayer layer,
            dynamic data,
            int width,
            int height,
            int depth)
        {
            int owidth  = width;
            int oheight = height;

            width  = 128 * TraceScale;
            height = 128 * TraceScale;
            depth  = 128 * TraceScale;

            Bitmap   b = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(b);

            g.Clear(Color.White);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;

            StorageLayer parent;

            if (layer.GetInputs().Length == 0)
            {
                parent = null;
            }
            else
            {
                parent = StorageAccess.FromRuntime(layer.GetInputs()[0]);
            }

            int[] render  = GetCellRenderOrder(RenderToNE, TraceRenderWidth, TraceRenderHeight);
            int   ztop    = layer.Algorithm.Is2DOnly ? 1 : 128;
            int   zbottom = 0;

            for (int z = zbottom; z < ztop; z++)
            {
                int rcx = width / 2 - 1;
                int rcy = height / 2 - (height / 2 - 1);
                int rw  = 2;
                int rh  = 1;
                for (int i = 0; i < render.Length; i++)
                {
                    // Calculate the X / Y of the tile in the grid.
                    int x = render[i] % TraceRenderWidth;
                    int y = render[i] / TraceRenderWidth;

                    // Calculate the render position on screen.
                    int rx = rcx + (int)((x - y) / 2.0 * rw);// (int)(x / ((RenderWidth + 1) / 2.0) * rw);
                    int ry = rcy + (x + y) * rh - (rh / 2 * (TraceRenderWidth + TraceRenderHeight)) - (z - zbottom) * 1;

                    while (true)
                    {
                        try
                        {
                            Color lc = layer.Algorithm.GetColorForValue(
                                parent,
                                data[x + y * owidth + z * owidth * oheight]);
                            SolidBrush sb = new SolidBrush(Color.FromArgb(lc.A, lc.R, lc.G, lc.B));
                            g.FillRectangle(
                                sb,
                                new Rectangle(rx, ry, rw, rh)
                                );
                            break;
                        }
                        catch (InvalidOperationException)
                        {
                            // Graphics can be in use elsewhere, but we don't care; just try again.
                        }
                    }
                }
            }

            return(b);
        }
 public IndexModel(StorageAccess storage)
 {
     _storage = storage;
 }
예제 #25
0
 public unsafe int OpenPropertyStoreNative(StorageAccess access, out IntPtr propertyStore)
 {
     propertyStore = IntPtr.Zero;
     fixed (void* pps = &propertyStore)
     {
         return InteropCalls.CallI(_basePtr, unchecked(access), pps, ((void**)(*(void**)_basePtr))[4]);
     }
 }
예제 #26
0
        public static void ReceiveStationOperation(BinaryReader reader, int sender)
        {
            if (Main.netMode != 2)
            {
                return;
            }
            int ent = reader.ReadInt32();

            if (!TileEntity.ByID.ContainsKey(ent) || !(TileEntity.ByID[ent] is TECraftingAccess))
            {
                return;
            }
            TECraftingAccess access = (TECraftingAccess)TileEntity.ByID[ent];

            Item[] stations = access.stations;
            byte   op       = reader.ReadByte();

            if (op == 0)
            {
                Item item = ItemIO.Receive(reader, true);
                access.TryDepositStation(item);
                if (item.stack > 0)
                {
                    ModPacket packet = PrepareStationResult(op);
                    ItemIO.Send(item, packet, true);
                    packet.Send(sender);
                }
            }
            else if (op == 1)
            {
                int  slot = reader.ReadByte();
                Item item = access.TryWithdrawStation(slot);
                if (!item.IsAir)
                {
                    ModPacket packet = PrepareStationResult(op);
                    ItemIO.Send(item, packet, true);
                    packet.Send(sender);
                }
            }
            else if (op == 2)
            {
                Item item = ItemIO.Receive(reader, true);
                int  slot = reader.ReadByte();
                item = access.DoStationSwap(item, slot);
                if (!item.IsAir)
                {
                    ModPacket packet = PrepareStationResult(op);
                    ItemIO.Send(item, packet, true);
                    packet.Send(sender);
                }
            }
            Point16       pos     = access.Position;
            StorageAccess modTile = TileLoader.GetTile(Main.tile[pos.X, pos.Y].type) as StorageAccess;

            if (modTile != null)
            {
                TEStorageHeart heart = modTile.GetHeart(pos.X, pos.Y);
                if (heart != null)
                {
                    SendRefreshNetworkItems(heart.ID);
                }
            }
        }
        private static Bitmap Regenerate3DImageForLayer(RuntimeLayer runtimeLayer, long ox, long oy, long oz, int width, int height, int depth, IGenerator compiledLayer = null)
        {
            int owidth  = width;
            int oheight = height;

            width  = 128;
            height = 192; // this affects bitmaps and rendering and stuff :(
            depth  = 128;

            // ARGHGHG FIXME
            Bitmap   b = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(b);

            g.Clear(Color.White);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
            int     computations = 0;
            dynamic data;

            if (compiledLayer != null)
            {
                data = compiledLayer.GenerateData(ox, oy, oz, RenderWidth, RenderHeight, RenderDepth, out computations);
            }
            else
            {
                data = runtimeLayer.GenerateData(ox, oy, oz, RenderWidth, RenderHeight, RenderDepth, out computations);
            }

            StorageLayer parent;

            if (runtimeLayer.GetInputs().Length == 0)
            {
                parent = null;
            }
            else
            {
                parent = StorageAccess.FromRuntime(runtimeLayer.GetInputs()[0]);
            }

            int[] render  = GetCellRenderOrder(RenderToNE, RenderWidth, RenderHeight);
            int   ztop    = runtimeLayer.Algorithm.Is2DOnly ? 1 : RenderDepth;
            int   zbottom = 0;

            for (int z = zbottom; z < ztop; z++)
            {
                int rcx = width / 2 - 1;
                int rcy = height / 2 - 31;
                int rw  = 2;
                int rh  = 1;
                for (int i = 0; i < render.Length; i++)
                {
                    // Calculate the X / Y of the tile in the grid.
                    int x = render[i] % RenderWidth;
                    int y = render[i] / RenderWidth;

                    // Calculate the render position on screen.
                    int rx = rcx + (int)((x - y) / 2.0 * rw);// (int)(x / ((RenderWidth + 1) / 2.0) * rw);
                    int ry = rcy + (x + y) * rh - (rh / 2 * (RenderWidth + RenderHeight)) - (z - zbottom) * 1;

                    while (true)
                    {
                        try
                        {
                            Color lc = runtimeLayer.Algorithm.GetColorForValue(
                                parent,
                                data[x + y * owidth + z * owidth * oheight]);
                            SolidBrush sb = new SolidBrush(Color.FromArgb(lc.A, lc.R, lc.G, lc.B));
                            g.FillRectangle(
                                sb,
                                new Rectangle(rx, ry, rw, rh)
                                );
                            break;
                        }
                        catch (InvalidOperationException)
                        {
                            // Graphics can be in use elsewhere, but we don't care; just try again.
                        }
                    }
                }
            }

            return(b);
        }
예제 #28
0
        protected override void ProcessGeneration(GenerationResult result, HttpContext context)
        {
            var cache = this.GetCacheName(result.Request, context, "json");

            context.Response.ContentType = "application/json";
            using (var cacheWriter = new StreamWriter(cache))
            {
                using (var webWriter = new StreamWriter(context.Response.OutputStream))
                {
                    if (result.Request.Packed)
                    {
                        cacheWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":true,\"data\":[");
                        webWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":true,\"data\":[");
                        {
                            var continuousValue = 0;
                            var continuousCount = 1;
                            var first           = true;
                            var i = 0;
                            do
                            {
                                // Store the value into our continuity tracker.
                                if (i != result.Data.Length)
                                {
                                    continuousValue = result.Data[i];
                                }

                                // Increment to the next position.
                                i++;

                                if (i == result.Data.Length ||
                                    continuousValue != result.Data[i])
                                {
                                    // Output in the most efficient manner.
                                    if (("[" + continuousCount + "," + continuousValue + "]").Length >
                                        ((continuousValue.ToString().Length + 1) * continuousCount) - 1)
                                    {
                                        // Single value.
                                        for (var a = 0; a < continuousCount; a++)
                                        {
                                            if (!first)
                                            {
                                                cacheWriter.Write(",");
                                                webWriter.Write(",");
                                            }
                                            first = false;

                                            cacheWriter.Write(continuousValue);
                                            webWriter.Write(continuousValue);
                                        }
                                    }
                                    else
                                    {
                                        if (!first)
                                        {
                                            cacheWriter.Write(",");
                                            webWriter.Write(",");
                                        }
                                        first = false;

                                        // Multiple copies of the same
                                        // value in a row.
                                        cacheWriter.Write("[" + continuousCount + "," + continuousValue + "]");
                                        webWriter.Write("[" + continuousCount + "," + continuousValue + "]");
                                    }

                                    // Reset the continity count.
                                    continuousCount = 1;
                                }
                                else
                                {
                                    continuousCount++;
                                }
                            } while (i < result.Data.Length);
                        }
                    }
                    else
                    {
                        cacheWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":false,\"data\":[");
                        webWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":false,\"data\":[");
                        {
                            var first = true;
                            for (var i = 0; i < result.Data.Length; i++)
                            {
                                if (!first)
                                {
                                    cacheWriter.Write(",");
                                    webWriter.Write(",");
                                }
                                first = false;
                                cacheWriter.Write(result.Data[i]);
                                webWriter.Write(result.Data[i]);
                            }
                        }
                    }
                    cacheWriter.Write("],\"mappings\":{");
                    webWriter.Write("],\"mappings\":{");
                    var mappings    = new Dictionary <int, Color>();
                    var parentLayer = StorageAccess.FromRuntime(result.Layer.GetInputs()[0]);
                    for (var i = 0; i < result.Data.Length; i++)
                    {
                        if (!mappings.ContainsKey(result.Data[i]))
                        {
                            mappings.Add(result.Data[i],
                                         result.Layer.Algorithm.GetColorForValue(
                                             parentLayer,
                                             result.Data[i]));
                        }
                    }
                    {
                        var first = true;
                        foreach (var kv in mappings)
                        {
                            if (!first)
                            {
                                cacheWriter.Write(",");
                                webWriter.Write(",");
                            }
                            first = false;

                            var colorString =
                                "[" + kv.Value.A +
                                "," + kv.Value.R +
                                "," + kv.Value.G +
                                "," + kv.Value.B + "]";
                            cacheWriter.Write("\"" + kv.Key + "\":" + colorString);
                            webWriter.Write("\"" + kv.Key + "\":" + colorString);
                        }
                    }
                    cacheWriter.Write("}}");
                    webWriter.Write("}}");
                }
            }
        }
예제 #29
0
        private static Bitmap RenderPartial3D(GenerationResult result)
        {
            var    width  = result.Request.Size;
            var    height = result.Request.Size;
            Bitmap bitmap;

            if (result.Request.AsSquare)
            {
                bitmap = new Bitmap(width, height - 1);
            }
            else
            {
                bitmap = new Bitmap(width * 2, height * 3);
            }
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
                var depth = result.Layer.Algorithm.Is2DOnly ? 1 : result.Request.Size;
                try
                {
                    var render      = GetCellRenderOrder(RenderToNE, width, height);
                    var ztop        = depth;
                    var zbottom     = 0;
                    var parentLayer = StorageAccess.FromRuntime(result.Layer.GetInputs()[0]);
                    for (int z = zbottom; z < ztop; z++)
                    {
                        int rcx = width / 2 - 1 + 32;
                        int rcy = height / 2 - 15 + 32;
                        int rw  = 2;
                        int rh  = 1;
                        for (int i = 0; i < render.Length; i++)
                        {
                            // Calculate the X / Y of the tile in the grid.
                            int x = render[i] % width;
                            int y = render[i] / width;

                            // Calculate the render position on screen.
                            int rx = rcx + (int)((x - y) / 2.0 * rw);
                            int ry = rcy + (x + y) * rh - (rh / 2 * (width + height)) - (z - zbottom) * 1;

                            // Adjust for square mode.
                            if (result.Request.AsSquare)
                            {
                                rx = (rx - rcx) + width / 2;
                                ry = (ry - rcy) - height / 2;
                                if (rx < -1 || ry < -1 ||
                                    rx > width + 1 || ry > height + 1)
                                {
                                    continue;
                                }
                            }

                            while (true)
                            {
                                try
                                {
                                    Color lc = result.Layer.Algorithm.GetColorForValue(
                                        parentLayer,
                                        result.Data[x + y * width + z * width * height]);
                                    var sb = new SolidBrush(Color.FromArgb(lc.A, lc.R, lc.G, lc.B));
                                    graphics.FillRectangle(sb, new Rectangle(rx, ry, rw, rh));
                                    break;
                                }
                                catch (InvalidOperationException)
                                {
                                    // Graphics can be in use elsewhere, but we don't care; just try again.
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
            return(bitmap);
        }