void DoContentsAndSettingsGui() { GUILayout.BeginHorizontal(); GUILayout.Label("Sample Text", EditorStyles.boldLabel); GUILayout.FlexibleSpace(); bool multiLine = (m_RegexOptions & RegexOptions.Multiline) > 0; EditorGUI.BeginChangeCheck(); multiLine = EditorGUILayout.Toggle("MultiLine", multiLine); if (EditorGUI.EndChangeCheck()) { m_RegexOptions = m_RegexOptions ^ RegexOptions.Multiline; m_ProcessedText = DoRegex(m_SampleText, m_RegexPattern.Value, m_RegexOptions); } GUILayout.EndHorizontal(); EditorGUI.BeginChangeCheck(); m_ContentsScroll = GUILayout.BeginScrollView(m_ContentsScroll); m_SampleText = EditorGUILayout.TextArea(m_SampleText, m_SampleTextStyle, GUILayout.ExpandHeight(true)); if (EditorGUI.EndChangeCheck()) { m_ProcessedText = DoRegex(m_SampleText, m_RegexPattern.Value, m_RegexOptions); } GUILayout.EndScrollView(); }
public static ProcessedText ConvertProcessTextRequestToProcessedTextDocument(ProcessTextRequest request) { var processedText = new ProcessedText { Id = request.Title, Author = request.Author, AutomatedReadabilityIndex = request.AutomatedReadabilityIndex, AverageSentenceLength = request.AverageSentenceLength, ColemanLiauIndex = request.ColemanLiauIndex, Content = request.Content, DaleChallReadabilityScore = request.DaleChallReadabilityScore, DatePublished = request.DatePublished, DifficultWords = request.DifficultWords, Domain = request.Domain, Excerpt = request.Excerpt, FleschKincaidGrade = request.FleschKincaidGrade, FleshEase = request.FleshEase, GunningFoxIndex = request.GunningFoxIndex, LeadImageUrl = request.LeadImageUrl, LexiconCount = request.LexiconCount, LinsearWriteIndex = request.LinsearWriteIndex, LixReadabilityIndex = request.LixReadabilityIndex, OverallScore = request.OverallScore, ProcessedTime = DateTime.UtcNow, SentenceCount = request.SentenceCount, SmogIndex = request.SmogIndex, SyllableCount = request.SyllableCount, Title = request.Title, Url = request.Url, }; return(processedText); }
public static GetTextResponse ConvertProcessedTextDocumentToGetTextResponse(ProcessedText document) { var getTextResponse = new GetTextResponse { Author = document.Author, AutomatedReadabilityIndex = document.AutomatedReadabilityIndex, AverageSentenceLength = document.AverageSentenceLength, ColemanLiauIndex = document.ColemanLiauIndex, Content = document.Content, DaleChallReadabilityScore = document.DaleChallReadabilityScore, DatePublished = document.DatePublished, DifficultWords = document.DifficultWords, Domain = document.Domain, Excerpt = document.Excerpt, FleschKincaidGrade = document.FleschKincaidGrade, FleshEase = document.FleshEase, GunningFoxIndex = document.GunningFoxIndex, LeadImageUrl = document.LeadImageUrl, LexiconCount = document.LexiconCount, LinsearWriteIndex = document.LinsearWriteIndex, LixReadabilityIndex = document.LixReadabilityIndex, OverallScore = document.OverallScore, ProcessedTime = document.ProcessedTime, SentenceCount = document.SentenceCount, SmogIndex = document.SmogIndex, Summary = document.Summary, Predicted = document.Predicted, SyllableCount = document.SyllableCount, Title = document.Title, Url = document.Url, }; return(getTextResponse); }
/// <summary>Load resources here.</summary> /// <param name="e">Not used.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.Keyboard.KeyDown += KeyDown; drawing = new QFontDrawing(); controlsDrawing = new QFontDrawing(); controlsTextOpts = new QFontRenderOptions() { Colour = Color.FromArgb(new Color4(0.8f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true }; heading2 = new QFont("woodenFont.qfont", new QFontConfiguration(addDropShadow: true), 1.0f); heading2Options = new QFontRenderOptions() { Colour = Color.White, DropShadowActive = true }; var builderConfig = new QFontBuilderConfiguration(addDropShadow: true); builderConfig.ShadowConfig.blurRadius = 2; //reduce blur radius because font is very small builderConfig.ShadowConfig.blurPasses = 1; builderConfig.ShadowConfig.Type = ShadowType.Blurred; builderConfig.TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit; //best render hint for this font builderConfig.Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic; mainText = new QFont("Fonts/times.ttf", 14, builderConfig); mainTextOptions = new QFontRenderOptions() { DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f }; _benchmarkResults = new QFont("Fonts/times.ttf", 14, builderConfig); heading1 = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true)); controlsText = new QFont("Fonts/HappySans.ttf", 32, new QFontBuilderConfiguration(true)); codeText = new QFont("Fonts/Comfortaa-Regular.ttf", 12, new QFontBuilderConfiguration()); heading1Options = new QFontRenderOptions() { Colour = Color.FromArgb(new Color4(0.2f, 0.2f, 0.2f, 1.0f).ToArgb()), DropShadowActive = true }; _processedText = QFontDrawingPrimitive.ProcessText(mainText, mainTextOptions, preProcessed, new SizeF(Width - 40, -1), QFontAlignment.Left); codeTextOptions = new QFontRenderOptions() { Colour = Color.FromArgb(new Color4(0.0f, 0.0f, 0.4f, 1.0f).ToArgb()) }; monoSpaced = new QFont("Fonts/Anonymous.ttf", 10, new QFontBuilderConfiguration()); monoSpacedOptions = new QFontRenderOptions() { Colour = Color.FromArgb(new Color4(0.1f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true }; GL.ClearColor(Color4.CornflowerBlue); }
public override void Load() { SceneManager.GameWindow.Cursor = MouseCursor.Empty; _stage = new Stage(this.SceneManager); _stage.ShaderProgram = _shaderProgram; _loadingFontRenderOptions = new QFontRenderOptions(); _loadingFontRenderOptions.DropShadowActive = true; _loadingFont = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Heading); _loadingFontDrawing = new QFontDrawing(); _loadingFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix; _loadingText = QFontDrawingPrimitive.ProcessText(_loadingFont.Font, _loadingFontRenderOptions, "Loading", new SizeF(200, -1), QFontAlignment.Centre); _loadingTextPosition = CalculateTextPosition(new Vector3((float)SceneManager.GameWindow.Width / 2, SceneManager.GameWindow.Height / 2, 0f), _loadingText); _songText = QFontDrawingPrimitive.ProcessText(_loadingFont.Font, _loadingFontRenderOptions, _song.SongBase.Identifier, new SizeF(SceneManager.GameWindow.Width - 40, -1), QFontAlignment.Centre); //Get difficulty options DifficultyOptions dOptions; switch ((DifficultyLevels)SceneManager.GameSettings["DifficultyLevel"]) { case DifficultyLevels.Easy: dOptions = DifficultyOptions.Easy; break; case DifficultyLevels.Medium: dOptions = DifficultyOptions.Medium; break; case DifficultyLevels.Hard: dOptions = DifficultyOptions.Hard; break; case DifficultyLevels.Ultra: dOptions = DifficultyOptions.Ultra; break; case DifficultyLevels.Ninja: dOptions = DifficultyOptions.Ninja; break; default: //shouldn't happen throw new Exception("Invalid difficulty level specified"); } var progress = new Progress <string>(status => { _loadingStatus = status; }); _loadTask = Task.Factory.StartNew(() => _stage.LoadAsync(_song, _audioCorrection, _maxAudioVolume, progress, _centerPolygon, _player, dOptions, (DifficultyLevels)SceneManager.GameSettings["DifficultyLevel"])); Loaded = true; }
static ProcessedText DoRegex(string source, string pattern, RegexOptions options) { ProcessedText processed = new ProcessedText(source, null, 0); if (string.IsNullOrEmpty(pattern) || string.IsNullOrEmpty(source)) { return(processed); } try { int inc = 0; StringBuilder sb = new StringBuilder(source); bool open = false; MatchCollection matches = Regex.Matches(source, pattern, options); processed.matchCount = matches.Count; for (int i = 0; i < matches.Count; i++) { Match match = matches[i]; if (!open) { sb.Insert(inc + match.Index, s_MatchColor); inc += 17; } open = i < matches.Count - 1 && match.Index + match.Length == matches[i + 1].Index; for (int n = inc + match.Index; n < inc + match.Index + match.Length; n++) { if (char.IsSeparator(sb[n])) { sb[n] = '→'; } } if (!open) { sb.Insert(inc + match.Index + match.Length, "</color>"); inc += 8; } } processed.text = sb.ToString(); } catch (System.Exception e) { processed.error = e.Message; } return(processed); }
public override void Load() { if (Font == null) { Font = _fontFile != null ? new QFont(_fontFile, _ptSize, _style) : new QFont(_innerFont); } Font.Options.TransformToViewport = Viewport; Font.Options.Colour = Color; if (!Dynamic) { _processedText = Font.ProcessText(Text, MaxWidth, Alignment); } }
public Text(string fileName) : base(fileName) { //var file = Resources.GetFile(ImageRootPath + Name); //Bitmap image = new Bitmap(file); //TextureID = GL.GenTexture(); //GL.BindTexture(TextureTarget.Texture2D, TextureID); //BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), // ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, // OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); //image.UnlockBits(data); //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); var builderConfig = new QFontBuilderConfiguration(true) { ShadowConfig = { BlurRadius = 2, BlurPasses = 1, Type = ShadowType.Blurred }, TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit, Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic }; //reduce blur radius because font is very small //best render hint for this font drawing = new QFontDrawing(); mainText = new QFont(fontRootPath + fileName + ".ttf", 14, builderConfig); mainTextOptions = new QFontRenderOptions { DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f }; processedText = QFontDrawingPrimitive.ProcessText(mainText, mainTextOptions, "Basldfgjwoietghwoifhewohfoiewuew", new SizeF(400 - 40, -1), QFontAlignment.Left); }
void ParseString() { int i = 0; int totalNull = 0; int fixIndex = 0; rawString = rawString.Replace(System.Environment.NewLine, ""); unsortedString = rawString.Split('#'); for (i = 0; i < unsortedString.Length; i++) { if (unsortedString[i].Length == 0 || unsortedString[i].Length == 1) { totalNull++; } } //sort string sortedTextAsset = new SortedTextAsset[unsortedString.Length - totalNull]; for (i = 0; i < unsortedString.Length; i++) { if (unsortedString[i].Length == 0 || unsortedString[i].Length == 1) { continue; } //Split depends of functionality sortedTextAsset[fixIndex] = new SortedTextAsset(); sortedTextAsset[fixIndex].textAsset = unsortedString[i].Split('@'); sortedTextAsset[fixIndex].RemoveNullString(); fixIndex++; } //assing string to ProcessedText processedText = new ProcessedText[sortedTextAsset.Length]; for (i = 0; i < sortedTextAsset.Length; i++) { processedText[i] = new ProcessedText(); processedText[i].soal = new VariableSoal[sortedTextAsset[i].textAsset.Length]; for (int j = 0; j < sortedTextAsset[i].textAsset.Length; j++) { string[] splittedText = sortedTextAsset[i].textAsset[j].Split(','); processedText[i].soal[j] = new VariableSoal(); processedText[i].soal[j].minVal = splittedText[0]; processedText[i].soal[j].maxVal = splittedText[1]; processedText[i].soal[j].delta = splittedText[2]; } } }
void DoSearchAndResultsGui() { GUILayout.BeginHorizontal(); GUILayout.Label("Pattern", EditorStyles.boldLabel); GUILayout.FlexibleSpace(); if (GUILayout.Button("cheatsheet")) { Application.OpenURL("https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx"); } if (GUILayout.Button("copy escaped pattern")) { GUIUtility.systemCopyBuffer = m_RegexPattern.Value.Replace("\\", "\\\\").Replace("\"", "\\\""); } GUILayout.EndHorizontal(); EditorGUI.BeginChangeCheck(); var pattern = m_RegexPattern.Value; // m_RegexPattern = EditorGUILayout.TextArea(m_RegexPattern, m_PatternSearchBox); EditorGUI.BeginChangeCheck(); pattern = EditorGUILayout.TextArea(pattern, m_PatternSearchBox); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(m_RegexPattern, "Regex Pattern Edit"); m_RegexPattern.Value = pattern; } if (EditorGUI.EndChangeCheck()) { m_ProcessedText = DoRegex(m_SampleText, m_RegexPattern.Value, m_RegexOptions); } GUILayout.Label("Matches (" + m_ProcessedText.matchCount + ")", EditorStyles.boldLabel); if (!string.IsNullOrEmpty(m_ProcessedText.error)) { EditorGUILayout.HelpBox(m_ProcessedText.error, MessageType.Error); } m_Scroll = GUILayout.BeginScrollView(m_Scroll); RenderText(m_ProcessedText.text, m_MatchesStyle); GUILayout.EndScrollView(); }
void OnEnable() { m_IsGuiInitialized = false; m_RegexPattern = CreateInstance <RegexInputString>(); m_RegexPattern.hideFlags = HideFlags.HideAndDontSave; m_RegexPattern.Value = "(?i)lorem"; m_ProcessedText = DoRegex(m_SampleText, m_RegexPattern.Value, m_RegexOptions); s_MatchColor = EditorGUIUtility.isProSkin ? "<color=#00FF00FF>" : "<color=#00DD00FF>"; Type splitterStateType = Type.GetType("UnityEditor.SplitterState, UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); m_SplitterState = Activator.CreateInstance( splitterStateType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { new float[] { .7f, .3f }, new int[] { 120, 22 }, null }, CultureInfo.CurrentCulture, null); Type splitterGuiLayoutType = Type.GetType("UnityEditor.SplitterGUILayout, UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); m_BeginVerticalSplit = splitterGuiLayoutType.GetMethod( "BeginVerticalSplit", BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, new Type[] { splitterStateType, typeof(GUILayoutOption[]) }, null); m_EndVerticalSplit = splitterGuiLayoutType.GetMethod( "EndVerticalSplit", BindingFlags.Static | BindingFlags.Public); m_SplitterArgs = new object[] { m_SplitterState, new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true) } }; Undo.undoRedoPerformed += Repaint; }
public static async Task <IActionResult> Run( [HttpTrigger( AuthorizationLevel.Function, "get", Route = null)] HttpRequest request, ILogger log, [CosmosDB( databaseName: "TextContent", collectionName: "Web", ConnectionStringSetting = "tkawchak-textanalysis_DOCUMENTDB", Id = "{Query.id}", PartitionKey = "{Query.domain}")] ProcessedText document) { log.LogInformation("C# GetProcessedText function received request."); if (document != null) { var response = Converters.ConvertProcessedTextDocumentToGetTextResponse(document); return(new OkObjectResult(response)); } else { return(new NotFoundObjectResult(request.Query)); } }
public IHttpActionResult Get(string fileExtension, string pathFile) { string content = null; try { string rootPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); string localPath = new Uri(rootPath).LocalPath; //is the file an rtf? if (fileExtension.ToLower() == "rtf") { RTFFormatter rtfF = new RTFFormatter(); content = rtfF.ReturnFormattedContent(Path.Combine(localPath, @"..\Data\", pathFile + "." + fileExtension)); } else { FileStream file = new FileStream(Path.Combine(localPath, @"..\Data\", pathFile + "." + fileExtension), FileMode.Open, FileAccess.Read); using (StreamReader sr = new StreamReader(file)) { content = sr.ReadToEnd(); content = Regex.Replace(content, "[\n]", Environment.NewLine); } } ProcessedText resultObj = new ProcessedText(content); //var json = new JavaScriptSerializer().Serialize(resultObj); return(Ok(resultObj)); } catch (Exception e) { return(InternalServerError(e)); } //return Ok(resultObj); }
public override void Process(List <Entity> entities, ) { String text = ExtensionText; text = text.Replace("{{^", "").Replace("^}}", ""); Regex wordCount = new Regex("(*?)"); if (wordCount.IsMatch(text) && new Regex("{*?}").IsMatch(text)) { Match match = wordCount.Match(text); ProcessedText.Replace(match.Value, ""); int count = int.Parse(match.Value.Replace("(", "").Replace(")", "")); match.NextMatch(); ProcessedText.Replace(match.Value, ""); String separator = match.Value.Replace("(", "").Replace(")", ""); List <String> words = new List <String>(text.Replace(match.Value, "").Replace("{", "").Replace("}", "").Split(',')); if (words.Count < count) { throw new Exception(String.Format("There is template Error: {0} Selected word counts is more than words written", ExtensionText)); } Random Shuffler = new Random(); int counter = 0; String result = ""; while (counter < count) { String word = words[Shuffler.Next(words.Count - counter - 1)]; result += word + separator; words.Remove(word); } ProcessedText = result; } else { throw new Exception(String.Format("There is template Error: {0} it should be {{^(select word count)(word separator){word1,word2,word3,word4....}^}} ", ExtensionText)); } }
/// <summary>Load resources here.</summary> /// <param name="e">Not used.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); _drawing = new QFontDrawing(); _controlsDrawing = new QFontDrawing(); _controlsTextOpts = new QFontRenderOptions { Colour = Color.FromArgb(new Color4(0.8f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true }; _heading2 = new QFont("woodenFont.qfont", new QFontConfiguration(true)); _heading2Options = new QFontRenderOptions { Colour = Color.White, DropShadowActive = true }; var builderConfig = new QFontBuilderConfiguration(true) { ShadowConfig = { BlurRadius = 2, BlurPasses = 1, Type = ShadowType.Blurred }, TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit, Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic }; //reduce blur radius because font is very small //best render hint for this font _mainText = new QFont("Fonts/times.ttf", 14, builderConfig); _mainTextOptions = new QFontRenderOptions { DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f }; _benchmarkResults = new QFont("Fonts/times.ttf", 14, builderConfig); _heading1 = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true)); _controlsText = new QFont("Fonts/HappySans.ttf", 32, new QFontBuilderConfiguration(true)); _codeText = new QFont("Fonts/Comfortaa-Regular.ttf", 12, new QFontBuilderConfiguration()); _heading1Options = new QFontRenderOptions { Colour = Color.FromArgb(new Color4(0.2f, 0.2f, 0.2f, 1.0f).ToArgb()), DropShadowActive = true }; _processedText = QFontDrawingPrimitive.ProcessText(_mainText, _mainTextOptions, _preProcessed, new SizeF(Width - 40, -1), QFontAlignment.Left); _codeTextOptions = new QFontRenderOptions { Colour = Color.FromArgb(new Color4(0.0f, 0.0f, 0.4f, 1.0f).ToArgb()) }; _monoSpaced = new QFont("Fonts/Anonymous.ttf", 10, new QFontBuilderConfiguration()); _monoSpacedOptions = new QFontRenderOptions { Colour = Color.FromArgb(new Color4(0.1f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true }; // loop through some installed fonts and load them var ifc = new InstalledFontCollection(); _installedFonts = new List <QFont>(); foreach (var fontFamily in ifc.Families) { // Don't load too many fonts if (_installedFonts.Count > 15) { break; } _installedFonts.Add(new QFont(fontFamily.Name, 14, new QFontBuilderConfiguration())); } GL.ClearColor(Color4.CornflowerBlue); }
/// <summary> /// Creates the image on an OpenGL 2D texture and returns it's OpenGL handle. /// This function creates and destroys all the OpenGL objects it uses except the texture and framebuffer. /// </summary> /// <param name="singular">The singular form of the word</param> /// <param name="plural">The plural form of the word</param> /// <param name="imagePath">The path to the image showing the word to use</param> /// <param name="fbo">The framebuffer object that was used to render to the returned texture, still with the texture attached in color0</param> /// <param name="WIDTH">The width of the texture</param> /// <param name="HEIGHT">The height of the texture</param> static int MakeAllImage(String singular, String plural, String imagePath, out int fbo, out int WIDTH, out int HEIGHT) { #if LOG_DATA DataLogger.Log("[ImageManager] MakeAllImage was called", LoggingMode.Message); #endif WIDTH = 800; GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusDstAlpha); #if LOG_DATA DataLogger.Log(String.Concat("[ImageManager] Loading bitmap from \"", imagePath, "\""), LoggingMode.Message); #endif Bitmap bitmap = new Bitmap(imagePath); #region CalculateTextColor #if LOG_DATA DataLogger.Log("[ImageManager] Calculating text color", LoggingMode.Message); #endif //calculate whether to make the *noise text* black or white based on the colors on the image. float diffX = bitmap.Width / (float)COLOR_CALCULATOR_SAMPLE_FREQ; float diffY = bitmap.Height / (float)COLOR_CALCULATOR_SAMPLE_FREQ; int grayscaleTotal = 0; for (float x = (bitmap.Width - bitmap.Width / COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ) / 2f; x < bitmap.Width; x += diffX) { for (float y = (bitmap.Height - bitmap.Height / COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ) / 2f; y < bitmap.Height; y += diffY) { Color c = bitmap.GetPixel((int)x, (int)y); grayscaleTotal += c.R; grayscaleTotal += c.G; grayscaleTotal += c.B; } } bool isBlack = grayscaleTotal / (COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ * 3) > 127; #if LOG_DATA DataLogger.Log("[ImageManager] Text color: " + (isBlack ? "black" : "white"), LoggingMode.Message); #endif #endregion #region LoadQFont #if LOG_DATA DataLogger.Log("[ImageManager] Loading QFont data", LoggingMode.Message); #endif QFontShadowConfiguration shadowConfig = new QFontShadowConfiguration() { Type = ShadowType.Expanded, BlurRadius = 2, }; QFontBuilderConfiguration qconfig = new QFontBuilderConfiguration(true) { SuperSampleLevels = 4, TextGenerationRenderHint = TextGenerationRenderHint.AntiAlias, }; QFont qfont = new QFont(new FreeTypeFont(FONT_LOCATION, 144, FontStyle.Regular), qconfig); QFontDrawing qdraw = new QFontDrawing(); QFontRenderOptions opts = new QFontRenderOptions() { CharacterSpacing = 0.06f, Colour = Color.Black, }; ProcessedText text = QFontDrawingPrimitive.ProcessText(qfont, opts, plural + " be like", new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Left); SizeF topTextSize = qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts); qdraw.RefreshBuffers(); #endregion int topHeight = 40 + (int)(topTextSize.Height + 0.5f); HEIGHT = WIDTH * bitmap.Height / bitmap.Width + topHeight; #if LOG_DATA DataLogger.Log(String.Concat("[ImageManager] WIDTH=", WIDTH, " HEIGHT=", HEIGHT, " topHeight=", topHeight), LoggingMode.Message); #endif #region GenVBO #if LOG_DATA DataLogger.Log("[ImageManager] Generating VBO and VAO", LoggingMode.Message); #endif float[] vboData = new float[] { 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0 }; int vbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo); GL.BufferData(BufferTarget.ArrayBuffer, vboData.Length * 4, vboData, BufferUsageHint.StaticDraw); int vao = GL.GenVertexArray(); GL.BindVertexArray(vao); GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 20, 0); GL.EnableVertexAttribArray(0); GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 20, 12); GL.EnableVertexAttribArray(1); #endregion #region LoadTexture #if LOG_DATA DataLogger.Log("[ImageManager] Generating texture for image", LoggingMode.Message); #endif int tex = GL.GenTexture(); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, tex); #if LOG_DATA DataLogger.Log("[ImageManager] Loading texture pixels from bitmap", LoggingMode.Message); #endif BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, bits.Scan0); bitmap.UnlockBits(bits); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); #endregion #region LoadShaderProgram #if LOG_DATA DataLogger.Log("[ImageManager] Creating shaders", LoggingMode.Message); #endif int vs = GL.CreateShader(ShaderType.VertexShader); #if LOG_DATA DataLogger.Log("[ImageManager] Loading vertex shader from " + VERTEX_SHADER_LOCATION, LoggingMode.Message); #endif GL.ShaderSource(vs, File.ReadAllText(VERTEX_SHADER_LOCATION)); GL.CompileShader(vs); int tmp; GL.GetShader(vs, ShaderParameter.CompileStatus, out tmp); #if LOG_DATA if (tmp != 1) { DataLogger.Log("[ImageManager] Vertex shader compilation failed", LoggingMode.Error); } DataLogger.Log("[ImageManager] Vertex Shader Info Log: ", LoggingMode.Message); DataLogger.Log(GL.GetShaderInfoLog(vs), LoggingMode.RawData); DataLogger.Log("[ImageManager] [END OF VERTEX SHADER INFO LOG]", LoggingMode.Message); #endif if (tmp != 1) { throw new Exception("Vertex Shader compilation failed. Process can't continue."); } int fs = GL.CreateShader(ShaderType.FragmentShader); #if LOG_DATA DataLogger.Log("[ImageManager] Loading fragment shader from " + FRAGMENT_SHADER_LOCATION, LoggingMode.Message); #endif GL.ShaderSource(fs, File.ReadAllText(FRAGMENT_SHADER_LOCATION)); GL.CompileShader(fs); GL.GetShader(fs, ShaderParameter.CompileStatus, out tmp); #if LOG_DATA if (tmp != 1) { DataLogger.Log("[ImageManager] Fragment shader compilation failed", LoggingMode.Error); } DataLogger.Log("[ImageManager] Fragment Shader Info Log: ", LoggingMode.Message); DataLogger.Log(GL.GetShaderInfoLog(fs), LoggingMode.RawData); DataLogger.Log("[ImageManager] [END OF FRAGMENT SHADER INFO LOG]", LoggingMode.Message); #endif if (tmp != 1) { throw new Exception("Fragment Shader compilation failed. Process can't continue."); } #if LOG_DATA DataLogger.Log("[ImageManager] Performing OpenGL program creation commands", LoggingMode.Message); #endif int program = GL.CreateProgram(); GL.AttachShader(program, vs); GL.AttachShader(program, fs); GL.BindAttribLocation(program, 0, "vPosition"); GL.BindAttribLocation(program, 1, "vTexCoords"); GL.LinkProgram(program); GL.DetachShader(program, vs); GL.DetachShader(program, fs); GL.DeleteProgram(vs); GL.DeleteProgram(fs); int texUniformLoc = GL.GetUniformLocation(program, "tex"); int projUniformLoc = GL.GetUniformLocation(program, "Proj"); GL.UseProgram(program); GL.GetProgram(program, GetProgramParameterName.LinkStatus, out tmp); #if LOG_DATA if (tmp != 1) { DataLogger.Log("[ImageManager] GL Program linking failed", LoggingMode.Error); } DataLogger.Log("[ImageManager] GL Program Info Log: ", LoggingMode.Message); DataLogger.Log(GL.GetProgramInfoLog(program), LoggingMode.RawData); DataLogger.Log("[ImageManager] [END OF GL PROGRAM INFO LOG]", LoggingMode.Message); DataLogger.Log("[ImageManager] Just a friendly reminder that GL PROGRAM refers to a OpenGL Shader Program with attached shaders", LoggingMode.Message); #endif if (tmp != 1) { throw new Exception("Program linking failed. Process can't continue."); } #endregion #region MakeResultTextureFramebuffer #if LOG_DATA DataLogger.Log("[ImageManager] Generating Framebuffer & Texture for rendering", LoggingMode.Message); #endif int resultTex = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, resultTex); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, WIDTH, HEIGHT, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); fbo = GL.GenFramebuffer(); GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, resultTex, 0); if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { //error #if LOG_DATA DataLogger.Log("[ImageManager] Framebuffer creation failed", LoggingMode.Error); #endif throw new Exception("Framebuffer creation failed. Process can't continue."); } #endregion #region Drawing #if LOG_DATA DataLogger.Log("[ImageManager] Performing OpenGL draw commands", LoggingMode.Message); #endif GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo); GL.ClearColor(1f, 1f, 1f, 1f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.UseProgram(program); Matrix4 mat = Matrix4.CreateOrthographicOffCenter(0, 1, 0, 1, -1, 1); GL.UniformMatrix4(projUniformLoc, false, ref mat); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, tex); GL.Uniform1(texUniformLoc, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo); GL.BindVertexArray(vao); GL.Viewport(0, 0, WIDTH, HEIGHT - topHeight); GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4); GL.Viewport(0, HEIGHT - topHeight, WIDTH, topHeight); qdraw.ProjectionMatrix = Matrix4.CreateTranslation(TEXT_BORDER_SPACE, topTextSize.Height + TEXT_BORDER_SPACE, 0) * Matrix4.CreateOrthographicOffCenter(0, WIDTH, 0, topHeight, -1, 1); qdraw.Draw(); GL.Viewport(0, 0, WIDTH, HEIGHT - topHeight); opts.DropShadowActive = true; opts.DropShadowColour = Color.White; opts.DropShadowOffset = Vector2.Zero;//new Vector2(-0.12f, 0.12f); text = QFontDrawingPrimitive.ProcessText(qfont, opts, String.Concat("*", singular, " noises*"), new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Centre); SizeF noiseTextSize = qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts); float textScale = Math.Min((WIDTH - TEXT_BORDER_SPACE * 4) / noiseTextSize.Width, (HEIGHT - TEXT_BORDER_SPACE * 4) / noiseTextSize.Height); #if LOG_DATA DataLogger.Log("[ImageManager] Updating QFont size (disposing and reloading)", LoggingMode.Message); #endif qfont.Dispose(); qconfig.ShadowConfig = shadowConfig; qfont = new QFont(new FreeTypeFont(FONT_LOCATION, 144 * textScale, FontStyle.Regular), qconfig); qdraw.DrawingPrimitives.Clear(); opts.Colour = isBlack ? Color.Black : Color.White; opts.DropShadowColour = isBlack ? Color.White : Color.Black; text = QFontDrawingPrimitive.ProcessText(qfont, opts, String.Concat("*", singular, " noises*"), new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Centre); qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts); qdraw.ProjectionMatrix = Matrix4.CreateTranslation(WIDTH / 2f, noiseTextSize.Height * textScale / 2f + (HEIGHT - topHeight) / 2f, 0f) * Matrix4.CreateOrthographicOffCenter(0, WIDTH, 0, HEIGHT - topHeight, -1, 1); qdraw.RefreshBuffers(); qdraw.Draw(); #if LOG_DATA DataLogger.Log("[ImageManager] Done drawing", LoggingMode.Success); #endif #endregion #region Disposing #if LOG_DATA DataLogger.Log("[ImageManager] Disposing MakeAllImage resources", LoggingMode.Message); #endif bitmap.Dispose(); qfont.Dispose(); qdraw.Dispose(); GL.DeleteProgram(program); GL.DeleteTexture(tex); GL.DeleteBuffer(vbo); GL.DeleteVertexArray(vao); #endregion #if LOG_DATA DataLogger.Log("[ImageManager] MakeAllImage is done. Returning texture and framebuffer data", LoggingMode.Message); #endif return(resultTex); }
private Vector3 CalculateTextPosition(Vector3 center, ProcessedText text) { var size = _loadingFont.Font.Measure(text); return(new Vector3(0, size.Height / 2, 0f)); }
public SizeF DrawProcessedText(ProcessedText pText, Vector3 position, Color4 colour) { return(FontDrawing.Print(DefaultFont.Font, pText, position, (Color)colour)); }
public override void Resize(EventArgs e) { _loadingText = QFontDrawingPrimitive.ProcessText(_loadingFont.Font, _loadingFontRenderOptions, "Loading", new SizeF(1000, -1), QFontAlignment.Centre); _loadingFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix; _loadingTextPosition = CalculateTextPosition(new Vector3(SceneManager.ScreenCamera.PreferredWidth / 2, SceneManager.ScreenCamera.PreferredHeight / 2, 0f), _loadingText); }