Repository: rafaskb/typing-label Branch: master Commit: c783d41e9867 Files: 48 Total size: 211.0 KB Directory structure: gitextract_7_7qo6u8/ ├── .gitignore ├── CHANGES ├── LICENSE ├── README.md ├── build.gradle ├── eclipse-formatter.xml ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml └── src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── rafaskoberg/ │ │ └── gdx/ │ │ └── typinglabel/ │ │ ├── Effect.java │ │ ├── GlyphUtils.java │ │ ├── InternalToken.java │ │ ├── Parser.java │ │ ├── TokenCategory.java │ │ ├── TokenDelimiter.java │ │ ├── TokenEntry.java │ │ ├── TypingAdapter.java │ │ ├── TypingConfig.java │ │ ├── TypingGlyph.java │ │ ├── TypingLabel.java │ │ ├── TypingListener.java │ │ ├── effects/ │ │ │ ├── BlinkEffect.java │ │ │ ├── EaseEffect.java │ │ │ ├── FadeEffect.java │ │ │ ├── GradientEffect.java │ │ │ ├── HangEffect.java │ │ │ ├── JumpEffect.java │ │ │ ├── RainbowEffect.java │ │ │ ├── ShakeEffect.java │ │ │ ├── SickEffect.java │ │ │ ├── SlideEffect.java │ │ │ ├── WaveEffect.java │ │ │ └── WindEffect.java │ │ └── utils/ │ │ ├── ColorUtils.java │ │ └── SimplexNoise.java │ └── resources/ │ └── com/ │ └── rafaskoberg/ │ └── gdx/ │ └── typinglabel/ │ └── typinglabel.gwt.xml └── test/ ├── java/ │ └── com/ │ └── rafaskoberg/ │ └── gdx/ │ └── typinglabel/ │ └── TypingLabelTest.java └── resources/ ├── arial18.fnt ├── default.fnt ├── text/ │ ├── colors.txt │ ├── default.txt │ ├── gender_pronouns.txt │ └── gender_pronouns_defaults.txt ├── uiskin.atlas └── uiskin.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ## Java *.class *.war *.ear hs_err_pid* replay_pid* ## GWT war/ html/war/gwt_bree/ html/gwt-unitCache/ .apt_generated/ html/war/WEB-INF/deploy/ html/war/WEB-INF/classes/ .gwt/ gwt-unitCache/ www-test/ .gwt-tmp/ ## Android Studio and Intellij and Android in general android/libs/armeabi/ android/libs/armeabi-v7a/ android/libs/x86/ android/gen/ .idea/ *.ipr *.iws *.iml out/ com_crashlytics_export_strings.xml ## Eclipse .classpath .project .metadata **/bin/ bin/ tmp/ *.tmp *.bak *.swp *~.nib local.properties .settings/ .loadpath .externalToolBuilders/ *.launch ## NetBeans **/nbproject/private/ build/ nbbuild/ dist/ nbdist/ nbactions.xml nb-configuration.xml ## Gradle .gradle build/ ## OS Specific .DS_Store docs/ ================================================ FILE: CHANGES ================================================ [Unreleased] - Nothing here so far. [1.4.0] - BREAKING CHANGE: Added support for multiple TypingListeners in TypingLabel. Methods "getTypingListener" and "getTypingListeners" were replaced by "setTypingListener" and "addTypingListener". - Added If Conditionals! {IF=GENDER;f=She;m=He;t=Them;Unknown} -- See details in the wiki. - Updated Regexodus dependency for GWT. If you use GWT and inherit Regexodus in your project, follow the installation instructions again, as some of them have changed (namely the `inherits` line). - Fixed color tags being applied to the incorrect glyph indices. Thanks @tommyettinger! - Fixed alpha not being applied to glyphs not affected by color-altering tokens. Thanks @tommyettinger! [1.3.0] - Fixed Windows line breaks (CR/LF) causing effect tokens to skip characters. This was mostly noticeable when loading strings from a text file. - Added `TokenDelimiter` configuration to `TypingConfig`, allowing users to change the token syntax. {CurlyBrackets}, [Brackets], and (Parentheses) are supported. - TypingLabel now depends on libGDX 1.11.0, because of differences in how it handles text internally (which this depends on). If you need compatibility with libGDX 1.9.9 through 1.10.0, you must use version 1.2.0 at the latest. [1.2.0] - API Addition: Added isSkipping method to TypingLabel class. - Fixed exception being thrown when parsing malformed color values from token arguments. - Fixed longer texts not being processed correctly after a setText call. Labels will now restart automatically after a setText call and will also skip to the end in case their progression has already ended. - Fixed issue causing labels not to align properly to the X axis. - Fixed some issues related to extreme frame rates, both high and low. Now the effects should remain the same independent of the FPS. - Fixed color tokens not detecting hex codes without a hash character. - Added new SLIDE effect. - Added new HANG effect. [1.1.0] - Added global variables that can be set in TypingConfig.GLOBAL_VARS. - API Change: Effect::onApply now takes a TypingGlyph instead of Glyph. This might break custom effects. - Added new RAINBOW effect. - Added new GRADIENT effect. - Added new FADE effect. - Added new BLINK effect. - Added ENDCOLOR token, an alias of CLEARCOLOR, to be consistent with the rest of the tokens. [1.0.7] - Added new WIND effect. - Added proper support to HTML / GWT by using RegExodus, thanks tommyettinger! See https://github.com/rafaskb/typing-label/pull/12 [1.0.6] - Fixed bug causing glyphs to appear completely out of place. [1.0.5] - Added new SICK effect. - Fixed nasty bug causing effects to affect the wrong glyphs after line breaks due to line wraps not being accounted for. - Added support for custom effect tokens. - API Addition: Added registerEffect and unregisterEffect methods to TypingConfig. [1.0.4] - Fixed bug causing last glyph to be rendered as the first one in some cases. [1.0.3] - API Addition: Notify listener about character progression through the method onChar(Character). - API Addition: Added cancelSkipping(), which can be called during events after skipToTheEnd() is called. - Fixed variables not being replaced without having a listener set. - Fixed exception when using null as text. [1.0.2] - Added a way to replace variables through a listener method, instead of having to provide fixed values. - Effect tokens now end previous effects of the same type, to prevent similar effects to stack. - Dispose cached glyphs when label is removed from its parent. - Fixed bug causing restart() to not actually restart the text when called from listener.end(). - Fixed bug causing weird effects to glyphs, especially on wrapped labels. - Fixed text effects ending at the wrong character. - Fixed events being fired at the wrong character. [1.0.1] - Added option to ignore events and effects while skipping to the end. - Fixed exception being thrown when the text reached the end. - Fixed {WAIT} tokens pausing the text one glyph ahead its position. - Fixed TypingLabel.end() being called too many times. - Forced all labels to calculate their full layouts. This fixes a bug causing one-line labels to not being rendered at all. - Fixed error when creating an empty label. [1.0.0] - Initial code ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Rafael Skoberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ ![Typing Label Logo](logo.png) # TypingLabel [![Maven Central](https://img.shields.io/maven-central/v/com.rafaskoberg.gdx/typing-label.svg?colorB=43BD15)](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22typing-label%22) [![license](https://img.shields.io/github/license/rafaskb/typing-label.svg)](https://github.com/rafaskb/typing-label/blob/master/LICENSE) A libGDX Label that appears as if it was being typed in real time. It works as a drop-in replacement for normal [Scene2D Labels](https://libgdx.com/wiki/graphics/2d/scene2d/scene2d-ui#label), and you can use optional [tokens](https://github.com/rafaskb/typing-label/wiki/Tokens) to customize the text's behavior. ![Sample GIF](media/sample.gif) ## Installation Open _build.gradle_ in project root and add this to the _ext_ section under _allprojects_: ```groovy typingLabelVersion = '1.4.0' regExodusVersion = '0.1.13' // Only if you're using HTML / GWT ``` #### Core module Add this to your _build.gradle_ core dependencies: ```groovy api "com.rafaskoberg.gdx:typing-label:$typingLabelVersion" ``` > _Note: Replace `api` with `compile` if you're using a Gradle version older than 3.4._ #### HTML dependencies ###### (Only if you're using HTML / GWT) Add this to your _GdxDefinition.gwt.xml_ file: ```xml ``` Add this to your _build.gradle_ html dependencies: ```groovy api "com.github.tommyettinger:regexodus:$regExodusVersion:sources" api "com.rafaskoberg.gdx:typing-label:$typingLabelVersion:sources" ``` > _Note: Replace `api` with `compile` if you're using a Gradle version older than 3.4._ ## Getting Started Check the Wiki: - [Usage examples](https://github.com/rafaskb/typing-label/wiki/Examples) - [Tokens](https://github.com/rafaskb/typing-label/wiki/Tokens) - [Fine tuning](https://github.com/rafaskb/typing-label/wiki/Fine-Tuning) - [Custom Effects](https://github.com/rafaskb/typing-label/wiki/Tokens#custom-effects) ## textratypist and SDF / MSDF Support _Multi-channel Signed Distance Field_ fonts allow you to prepare and load just one font file and render it in any scale you want, while mantaining the quality and cripsness of the original texture, as if you were working directly with vectors. Since TypingLabel aims to be a replacement for regular scene2d.ui Labels though, that means it relies on BitmapFonts, which have a specific size and don't work well with scaling. If you're using SDF fonts in your project and want TypingLabel features, then make sure to take a look at [Textramode](https://github.com/tommyettinger/textramode) and [Textratypist](https://github.com/tommyettinger/textramode) libraries by [Tommy Ettinger](https://github.com/tommyettinger). They support SDF and MSDF fonts, have much of the TypingLabel features, as well extended markup such as bold and oblique, and much more. ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenLocal() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } gradlePluginPortal() } dependencies { classpath 'com.vanniktech:gradle-maven-publish-plugin:0.17.0' } } apply plugin: 'java-library' apply plugin: 'com.vanniktech.maven.publish' sourceCompatibility = 1.7 def projectName = 'typing-label' version "$VERSION_NAME" group 'com.rafaskoberg.gdx' [compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8' // Disable JDK 8's doclint // http://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html if (JavaVersion.current().isJava8Compatible()) { allprojects { tasks.withType(Javadoc) { // The -quiet is because of some sort of weird JDK JavaCompiler bug: // https://discuss.gradle.org/t/passing-arguments-to-compiler-and-javadoc/1661 options.addStringOption('Xdoclint:none,-missing', '-quiet') } } } if(JavaVersion.current().isJava9Compatible()) { allprojects { tasks.withType(JavaCompile) { options.release.set(7) } } } sourceSets.test.resources.srcDirs = [ file('src/test/resources').path ] javadoc.destinationDir = file('docs/apidocs') jar { duplicatesStrategy(DuplicatesStrategy.EXCLUDE) archiveBaseName.set(projectName) manifest { attributes 'Implementation-Title': projectName, 'Implementation-Version': archiveVersion } } repositories { mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } dependencies { api group: 'com.badlogicgames.gdx', name: 'gdx', version: gdxVersion api group: 'com.github.tommyettinger', name: 'regexodus', version: regExodusVersion testImplementation group: 'com.badlogicgames.gdx', name: 'gdx-backend-lwjgl', version: gdxVersion testImplementation group: 'com.badlogicgames.gdx', name: 'gdx-platform', version: gdxVersion, classifier: 'natives-desktop' } ================================================ FILE: eclipse-formatter.xml ================================================ ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ org.gradle.daemon=true org.gradle.jvmargs=-Xms128m -Xmx512m -Dfile.encoding=UTF-8 -Dconsole.encoding=UTF-8 org.gradle.configureondemand=false gdxVersion=1.11.0 regExodusVersion=0.1.15 GROUP=com.rafaskoberg.gdx POM_ARTIFACT_ID=typing-label VERSION_NAME=1.4.1-SNAPSHOT POM_NAME=typing-label POM_DESCRIPTION=A libGDX Label that appears as if it was being typed in real time. POM_INCEPTION_YEAR=2017 POM_URL=https://github.com/rafaskb/typing-label/ POM_SCM_URL=https://github.com/rafaskb/typing-label/ POM_SCM_CONNECTION=scm:https://rafaskb@github.com/rafaskb/typing-label.git POM_SCM_DEV_CONNECTION=scm:git://github.com/rafaskb/typing-label.git POM_LICENCE_NAME=The MIT License (MIT) POM_LICENCE_URL=https://mit-license.org/ POM_LICENCE_DIST=repo POM_DEVELOPER_ID=rafaskb POM_DEVELOPER_NAME=Rafa Skoberg POM_DEVELOPER_URL=https://github.com/rafaskb/ POM_DEVELOPER_EMAIL=rafa.skoberg@gmail.com ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: jitpack.yml ================================================ jdk: - openjdk16 install: - echo "Installing with Gradle" - chmod 755 gradlew - ./gradlew clean publishToMavenLocal -x signMavenPublication ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/Effect.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; /** Abstract text effect. */ public abstract class Effect { private static final float FADEOUT_SPLIT = 0.25f; protected final TypingLabel label; public int indexStart = -1; public int indexEnd = -1; public float duration = Float.POSITIVE_INFINITY; protected float totalTime; public Effect(TypingLabel label) { this.label = label; } public void update(float delta) { totalTime += delta; } /** Applies the effect to the given glyph. */ public final void apply(TypingGlyph glyph, int glyphIndex, float delta) { int localIndex = glyphIndex - indexStart; onApply(glyph, localIndex, delta); } /** Called when this effect should be applied to the given glyph. */ protected abstract void onApply(TypingGlyph glyph, int localIndex, float delta); /** Returns whether or not this effect is finished and should be removed. Note that effects are infinite by default. */ public boolean isFinished() { return totalTime > duration; } /** Calculates the fadeout of this effect, if any. Only considers the second half of the duration. */ protected float calculateFadeout() { if(Float.isInfinite(duration)) return 1; // Calculate raw progress float progress = MathUtils.clamp(totalTime / duration, 0, 1); // If progress is before the split point, return a full factor if(progress < FADEOUT_SPLIT) return 1; // Otherwise calculate from the split point return Interpolation.smooth.apply(1, 0, (progress - FADEOUT_SPLIT) / (1f - FADEOUT_SPLIT)); } /** * Calculates a linear progress dividing the total time by the given modifier. Returns a value between 0 and 1 that * loops in a ping-pong mode. */ protected float calculateProgress(float modifier) { return calculateProgress(modifier, 0, true); } /** * Calculates a linear progress dividing the total time by the given modifier. Returns a value between 0 and 1 that * loops in a ping-pong mode. */ protected float calculateProgress(float modifier, float offset) { return calculateProgress(modifier, offset, true); } /** Calculates a linear progress dividing the total time by the given modifier. Returns a value between 0 and 1. */ protected float calculateProgress(float modifier, float offset, boolean pingpong) { float progress = totalTime / modifier + offset; while(progress < 0.0f) { progress += 2.0f; } if(pingpong) { progress %= 2f; if(progress > 1.0f) progress = 1f - (progress - 1f); } else { progress %= 1.0f; } progress = MathUtils.clamp(progress, 0, 1); return progress; } /** Returns the line height of the label controlling this effect. */ protected float getLineHeight() { return label.getBitmapFontCache().getFont().getLineHeight() * label.getFontScaleY(); } /** Returns a float value parsed from the given String, or the default value if the string couldn't be parsed. */ protected float paramAsFloat(String str, float defaultValue) { return Parser.stringToFloat(str, defaultValue); } /** Returns a boolean value parsed from the given String, or the default value if the string couldn't be parsed. */ protected boolean paramAsBoolean(String str) { return Parser.stringToBoolean(str); } /** Parses a color from the given string. Returns null if the color couldn't be parsed. */ protected Color paramAsColor(String str) { return Parser.stringToColor(str); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/GlyphUtils.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.ReflectionPool; /** Utility class to manage {@link Glyph} pooling and cloning. */ class GlyphUtils { private static final Pool pool = new ReflectionPool(TypingGlyph.class) { protected void reset(TypingGlyph glyph) { GlyphUtils.reset(glyph); } }; /** * Returns a glyph from this pool. The glyph may be new (from {@link Pool#newObject()}) or reused (previously {@link * Pool#free(Object) freed}). */ static TypingGlyph obtain() { return pool.obtain(); } /** * Returns a glyph from this pool and clones it from the given one. The glyph may be new (from {@link * Pool#newObject()}) or reused (previously {@link Pool#free(Object) freed}). */ static Glyph obtainClone(Glyph from) { TypingGlyph glyph = pool.obtain(); clone(from, glyph); return glyph; } /** * Puts the specified glyph in the pool, making it eligible to be returned by {@link #obtain()}. If the pool already * contains {@link Pool#max} free glyphs, the specified glyph is reset but not added to the pool. */ static void free(TypingGlyph glyph) { pool.free(glyph); } /** * Puts the specified glyphs in the pool. Null glyphs within the array are silently ignored. * * @see Pool#free(Object) */ static void freeAll(Array glyphs) { pool.freeAll(glyphs); } /** Called when a glyph is freed to clear the state of the glyph for possible later reuse. */ static void reset(TypingGlyph glyph) { glyph.id = 0; glyph.srcX = 0; glyph.srcY = 0; glyph.width = 0; glyph.height = 0; glyph.u = 0; glyph.v = 0; glyph.u2 = 0; glyph.v2 = 0; glyph.xoffset = 0; glyph.yoffset = 0; glyph.xadvance = 0; glyph.kerning = null; glyph.fixedWidth = false; glyph.runColor = 0xFFFFFFFF; glyph.internalIndex = -1; glyph.color = null; } /** Copies all contents from the first glyph to the second one. */ static void clone(Glyph from, TypingGlyph to) { to.id = from.id; to.srcX = from.srcX; to.srcY = from.srcY; to.width = from.width; to.height = from.height; to.u = from.u; to.v = from.v; to.u2 = from.u2; to.v2 = from.v2; to.xoffset = from.xoffset; to.yoffset = from.yoffset; to.xadvance = from.xadvance; to.kerning = from.kerning; // Keep the same instance, there's no reason to deep clone it to.fixedWidth = from.fixedWidth; to.runColor = 0xFFFFFFFF; to.internalIndex = -1; to.color = null; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/InternalToken.java ================================================ package com.rafaskoberg.gdx.typinglabel; enum InternalToken { // @formatter:off // Public WAIT ("WAIT", TokenCategory.WAIT ), SPEED ("SPEED", TokenCategory.SPEED ), SLOWER ("SLOWER", TokenCategory.SPEED ), SLOW ("SLOW", TokenCategory.SPEED ), NORMAL ("NORMAL", TokenCategory.SPEED ), FAST ("FAST", TokenCategory.SPEED ), FASTER ("FASTER", TokenCategory.SPEED ), COLOR ("COLOR", TokenCategory.COLOR ), CLEARCOLOR ("CLEARCOLOR", TokenCategory.COLOR ), ENDCOLOR ("ENDCOLOR", TokenCategory.COLOR ), VAR ("VAR", TokenCategory.VARIABLE ), IF ("IF", TokenCategory.IF ), EVENT ("EVENT", TokenCategory.EVENT ), RESET ("RESET", TokenCategory.RESET ), SKIP ("SKIP", TokenCategory.SKIP ); // @formatter:on final String name; final TokenCategory category; private InternalToken(String name, TokenCategory category) { this.name = name; this.category = category; } @Override public String toString() { return name; } static InternalToken fromName(String name) { if(name != null) { for(InternalToken token : values()) { if(name.equalsIgnoreCase(token.name)) { return token; } } } return null; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/Parser.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Colors; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Constructor; import com.badlogic.gdx.utils.reflect.ReflectionException; import regexodus.Matcher; import regexodus.Pattern; import regexodus.REFlags; /** Utility class to parse tokens from a {@link TypingLabel}. */ class Parser { private static TokenDelimiter CURRENT_DELIMITER = TypingConfig.TOKEN_DELIMITER; private static Pattern PATTERN_TOKEN_STRIP = compileTokenPattern(); private static Pattern PATTERN_MARKUP_STRIP = Pattern.compile("(\\[{2})|(\\[#?\\w*(\\[|\\])?)"); private static final Pattern PATTERN_COLOR_HEX_NO_HASH = Pattern.compile("[A-F0-9]{6}"); private static final String[] BOOLEAN_TRUE = {"true", "yes", "t", "y", "on", "1"}; private static final int INDEX_TOKEN = 1; private static final int INDEX_PARAM = 2; private static String RESET_REPLACEMENT; /** Parses all tokens from the given {@link TypingLabel}. */ static void parseTokens(TypingLabel label) { // Detect if token delimiter has changed boolean hasDelimiterChanged = CURRENT_DELIMITER != TypingConfig.TOKEN_DELIMITER; if(hasDelimiterChanged) { CURRENT_DELIMITER = TypingConfig.TOKEN_DELIMITER; } // Compile patterns if necessary if(PATTERN_TOKEN_STRIP == null || TypingConfig.dirtyEffectMaps || hasDelimiterChanged) { PATTERN_TOKEN_STRIP = compileTokenPattern(); } if(RESET_REPLACEMENT == null || TypingConfig.dirtyEffectMaps || hasDelimiterChanged) { RESET_REPLACEMENT = getResetReplacement(); } // Adjust and check markup color if(label.forceMarkupColor) label.getBitmapFontCache().getFont().getData().markupEnabled = true; // Remove any previous entries label.tokenEntries.clear(); // Parse all tokens with text replacements, namely color and var. parseReplacements(label); // Parse all regular tokens and properly register them parseRegularTokens(label); // Parse color markups and register SKIP tokens parseColorMarkups(label); // Sort token entries label.tokenEntries.sort(); label.tokenEntries.reverse(); } /** Parse tokens that only replace text, such as colors and variables. */ private static void parseReplacements(TypingLabel label) { // Get text CharSequence text = label.getText(); boolean hasMarkup = label.getBitmapFontCache().getFont().getData().markupEnabled; // Create string builder StringBuilder sb = new StringBuilder(text.length()); Matcher m = PATTERN_TOKEN_STRIP.matcher(text); int matcherIndexOffset = 0; // Iterate through matches while(true) { // Reset StringBuilder and matcher sb.setLength(0); m.setTarget(text); m.setPosition(matcherIndexOffset); // Make sure there's at least one regex match if(!m.find()) break; // Get token and parameter final InternalToken internalToken = InternalToken.fromName(m.group(INDEX_TOKEN)); final String param = m.group(INDEX_PARAM); // If token couldn't be parsed, move one index forward to continue the search if(internalToken == null) { matcherIndexOffset++; continue; } // Process tokens and handle replacement String replacement = ""; switch(internalToken) { case COLOR: if(hasMarkup) replacement = stringToColorMarkup(param); break; case ENDCOLOR: case CLEARCOLOR: if(hasMarkup) replacement = "[#" + label.getClearColor().toString() + "]"; break; case VAR: replacement = null; // Try to replace variable through listeners. for(TypingListener listener : label.getTypingListeners()) { replacement = listener.replaceVariable(param); if(replacement != null) break; } // If replacement is null, get value from maps. if(replacement == null) { replacement = label.getVariables().get(param.toUpperCase()); } // If replacement is still null, get value from global scope if(replacement == null) { replacement = TypingConfig.GLOBAL_VARS.get(param.toUpperCase()); } // Make sure we're not inserting "null" to the text. if(replacement == null) replacement = param.toUpperCase(); break; case IF: // Process token replacement = processIfToken(label, param); // Make sure we're not inserting "null" to the text. if(replacement == null) replacement = param.toUpperCase(); break; case RESET: replacement = RESET_REPLACEMENT + label.getDefaultToken(); break; default: // We don't want to process this token now. Move one index forward to continue the search matcherIndexOffset++; continue; } // Update text with replacement m.setPosition(m.start()); text = m.replaceFirst(replacement); } // Set new text label.setText(text, false, false); } private static String processIfToken(TypingLabel label, String paramsString) { // Split params final String[] params = paramsString == null ? new String[0] : paramsString.split(";"); final String variable = params.length > 0 ? params[0] : null; // Ensure our params are valid if(params.length <= 1 || variable == null) { return null; } /* Get variable's value */ String variableValue = null; // Try to get value through listener. for(TypingListener listener : label.getTypingListeners()) { variableValue = listener.replaceVariable(variable); if(variableValue != null) break; } // If value is null, get it from maps. if(variableValue == null) { variableValue = label.getVariables().get(variable.toUpperCase()); } // If value is still null, get it from global scope if(variableValue == null) { variableValue = TypingConfig.GLOBAL_VARS.get(variable.toUpperCase()); } // Ensure variable is never null if(variableValue == null) { variableValue = ""; } // Iterate through params and try to find a match String defaultValue = null; for(int i = 1, n = params.length; i < n; i++) { String[] subParams = params[i].split("=", 2); String key = subParams[0]; String value = subParams[subParams.length - 1]; boolean isKeyValid = subParams.length > 1 && !key.isEmpty(); // If key isn't valid, it must be a default value. Store it and carry on if(!isKeyValid) { defaultValue = value; break; } // Compare variable's value with key if(variableValue.equalsIgnoreCase(key)) { return value; } } // Try to return any default values captured during the iteration if(defaultValue != null) { return defaultValue; } // If we got this far, no values matched our variable. // Return the variable itself, which might be useful for debugging. return variable; } /** Parses regular tokens that don't need replacement and register their indexes in the {@link TypingLabel}. */ private static void parseRegularTokens(TypingLabel label) { // Get text CharSequence text = label.getText(); // Create matcher and StringBuilder Matcher m = PATTERN_TOKEN_STRIP.matcher(text); StringBuilder sb = new StringBuilder(text.length()); int matcherIndexOffset = 0; // Iterate through matches while(true) { // Reset matcher and StringBuilder m.setTarget(text); sb.setLength(0); m.setPosition(matcherIndexOffset); // Make sure there's at least one regex match if(!m.find()) break; // Get token name and category String tokenName = m.group(INDEX_TOKEN).toUpperCase(); TokenCategory tokenCategory = null; InternalToken tmpToken = InternalToken.fromName(tokenName); if(tmpToken == null) { if(TypingConfig.EFFECT_START_TOKENS.containsKey(tokenName)) { tokenCategory = TokenCategory.EFFECT_START; } else if(TypingConfig.EFFECT_END_TOKENS.containsKey(tokenName)) { tokenCategory = TokenCategory.EFFECT_END; } } else { tokenCategory = tmpToken.category; } // Get token, param and index of where the token begins int groupCount = m.groupCount(); final String paramsString = groupCount == INDEX_PARAM ? m.group(INDEX_PARAM) : null; final String[] params = paramsString == null ? new String[0] : paramsString.split(";"); final String firstParam = params.length > 0 ? params[0] : null; final int index = m.start(0); int indexOffset = 0; // If token couldn't be parsed, move one index forward to continue the search if(tokenCategory == null) { matcherIndexOffset++; continue; } // Process tokens float floatValue = 0; String stringValue = null; Effect effect = null; switch(tokenCategory) { case WAIT: { floatValue = stringToFloat(firstParam, TypingConfig.DEFAULT_WAIT_VALUE); break; } case EVENT: { stringValue = paramsString; indexOffset = -1; break; } case SPEED: { switch(tokenName) { case "SPEED": float minModifier = TypingConfig.MIN_SPEED_MODIFIER; float maxModifier = TypingConfig.MAX_SPEED_MODIFIER; float modifier = MathUtils.clamp(stringToFloat(firstParam, 1), minModifier, maxModifier); floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / modifier; break; case "SLOWER": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 0.500f; break; case "SLOW": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 0.667f; break; case "NORMAL": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR; break; case "FAST": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 2.000f; break; case "FASTER": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 4.000f; break; } break; } case EFFECT_START: { Class clazz = TypingConfig.EFFECT_START_TOKENS.get(tokenName.toUpperCase()); try { if(clazz != null) { Constructor constructor = ClassReflection.getConstructors(clazz)[0]; int constructorParamCount = constructor.getParameterTypes().length; if(constructorParamCount >= 2) { effect = (Effect) constructor.newInstance(label, params); } else { effect = (Effect) constructor.newInstance(label); } } } catch(ReflectionException e) { String message = "Failed to initialize " + tokenName + " effect token. Make sure the associated class (" + clazz + ") has only one constructor with TypingLabel as first parameter and optionally String[] as second."; throw new IllegalStateException(message, e); } break; } case EFFECT_END: { break; } } // Register token TokenEntry entry = new TokenEntry(tokenName, tokenCategory, index + indexOffset, floatValue, stringValue); entry.effect = effect; label.tokenEntries.add(entry); // Set new text without tokens m.setPosition(0); text = m.replaceFirst(""); } // Update label text label.setText(text, false, false); } /** Parse color markup tags and register SKIP tokens. */ private static void parseColorMarkups(TypingLabel label) { // Get text final CharSequence text = label.getText(); // Iterate through matches and register skip tokens Matcher m = PATTERN_MARKUP_STRIP.matcher(text); while(m.find()) { final String tag = m.group(0); final int index = m.start(0); label.tokenEntries.add(new TokenEntry("SKIP", TokenCategory.SKIP, index, 0, tag)); } } /** Returns a float value parsed from the given String, or the default value if the string couldn't be parsed. */ static float stringToFloat(String str, float defaultValue) { if(str != null) { try { return Float.parseFloat(str); } catch(Exception e) { } } return defaultValue; } /** Returns a boolean value parsed from the given String, or the default value if the string couldn't be parsed. */ static boolean stringToBoolean(String str) { if(str != null) { for(String booleanTrue : BOOLEAN_TRUE) { if(booleanTrue.equalsIgnoreCase(str)) { return true; } } } return false; } /** Parses a color from the given string. Returns null if the color couldn't be parsed. */ static Color stringToColor(String str) { if(str != null) { // Try to parse named color Color namedColor = Colors.get(str.toUpperCase()); if(namedColor != null) { return new Color(namedColor); } // Try to parse hex if(str.length() >= 6) { try { return Color.valueOf(str); } catch(NumberFormatException ignored) { } } } return null; } /** Encloses the given string in brackets to work as a regular color markup tag. */ private static String stringToColorMarkup(String str) { if(str != null) { // Upper case str = str.toUpperCase(); // If color isn't registered by name, try to parse it as an hex code. Color namedColor = Colors.get(str); if(namedColor == null) { boolean isHexWithoutHashChar = str.length() >= 6 && PATTERN_COLOR_HEX_NO_HASH.matches(str); if(isHexWithoutHashChar) { str = "#" + str; } } } // Return color code return "[" + str + "]"; } /** * Returns a compiled {@link Pattern} that groups the token name in the first group and the params in an optional second one. Case * insensitive. */ private static Pattern compileTokenPattern() { StringBuilder sb = new StringBuilder(); sb.append("\\").append(CURRENT_DELIMITER.open).append("("); Array tokens = new Array<>(); TypingConfig.EFFECT_START_TOKENS.keys().toArray(tokens); TypingConfig.EFFECT_END_TOKENS.keys().toArray(tokens); for(InternalToken token : InternalToken.values()) { tokens.add(token.name); } for(int i = 0; i < tokens.size; i++) { sb.append(tokens.get(i)); if((i + 1) < tokens.size) sb.append('|'); } sb.append(")(?:=([;:?=^_ #-'*-.\\.\\w]+))?\\").append(CURRENT_DELIMITER.close); return Pattern.compile(sb.toString(), REFlags.IGNORE_CASE); } /** Returns the replacement string intended to be used on {RESET} tokens. */ private static String getResetReplacement() { Array tokens = new Array<>(); TypingConfig.EFFECT_END_TOKENS.keys().toArray(tokens); tokens.add("CLEARCOLOR"); tokens.add("NORMAL"); StringBuilder sb = new StringBuilder(); for(String token : tokens) { sb.append(CURRENT_DELIMITER.open).append(token).append(CURRENT_DELIMITER.close); } return sb.toString(); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TokenCategory.java ================================================ package com.rafaskoberg.gdx.typinglabel; public enum TokenCategory { WAIT, SPEED, COLOR, VARIABLE, IF, EVENT, RESET, SKIP, EFFECT_START, EFFECT_END } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TokenDelimiter.java ================================================ package com.rafaskoberg.gdx.typinglabel; /** * Enum that lists all supported delimiters for tokens. */ public enum TokenDelimiter { /** {TOKEN} */ CURLY_BRACKETS('{', '}'), /** [TOKEN] */ BRACKETS('[', ']'), /** (TOKEN) */ PARENTHESES('(', ')'); public final char open; public final char close; TokenDelimiter(char open, char close) { this.open = open; this.close = close; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TokenEntry.java ================================================ package com.rafaskoberg.gdx.typinglabel; /** Container representing a token, parsed parameters and its position in text. */ class TokenEntry implements Comparable { String token; TokenCategory category; int index; float floatValue; String stringValue; Effect effect; TokenEntry(String token, TokenCategory category, int index, float floatValue, String stringValue) { this.token = token; this.category = category; this.index = index; this.floatValue = floatValue; this.stringValue = stringValue; } @Override public int compareTo(TokenEntry o) { return Integer.compare(index, o.index); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingAdapter.java ================================================ package com.rafaskoberg.gdx.typinglabel; /** Simple listener for label events. You can derive from this and only override what you are interested in. */ public class TypingAdapter implements TypingListener { @Override public void event(String event) { } @Override public void end() { } @Override public String replaceVariable(String variable) { return null; } @Override public void onChar(Character ch) { } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingConfig.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.utils.ObjectFloatMap; import com.badlogic.gdx.utils.ObjectMap; import com.rafaskoberg.gdx.typinglabel.effects.BlinkEffect; import com.rafaskoberg.gdx.typinglabel.effects.EaseEffect; import com.rafaskoberg.gdx.typinglabel.effects.FadeEffect; import com.rafaskoberg.gdx.typinglabel.effects.GradientEffect; import com.rafaskoberg.gdx.typinglabel.effects.HangEffect; import com.rafaskoberg.gdx.typinglabel.effects.JumpEffect; import com.rafaskoberg.gdx.typinglabel.effects.RainbowEffect; import com.rafaskoberg.gdx.typinglabel.effects.ShakeEffect; import com.rafaskoberg.gdx.typinglabel.effects.SickEffect; import com.rafaskoberg.gdx.typinglabel.effects.SlideEffect; import com.rafaskoberg.gdx.typinglabel.effects.WaveEffect; import com.rafaskoberg.gdx.typinglabel.effects.WindEffect; /** Configuration class that easily allows the user to fine tune the library's functionality. */ public class TypingConfig { /** * Whether or not LibGDX's Color Markup * Language should be enabled when parsing a {@link TypingLabel}. Note that this library doesn't truly handle * colors, but simply convert them to the markup format. If markup is disabled, color tokens will be ignored. */ public static boolean FORCE_COLOR_MARKUP_BY_DEFAULT = true; /** Default time in seconds that an empty {@code WAIT} token should wait for. Default value is {@code 0.250}. */ public static float DEFAULT_WAIT_VALUE = 0.250f; /** Time in seconds that takes for each char to appear in the default speed. Default value is {@code 0.035}. */ public static float DEFAULT_SPEED_PER_CHAR = 0.035f; /** * Minimum value for the {@code SPEED} token. This value divides {@link #DEFAULT_SPEED_PER_CHAR} to calculate the * final speed. Keep it above zero. Default value is {@code 0.001}. */ public static float MIN_SPEED_MODIFIER = 0.001f; /** * Maximum value for the {@code SPEED} token. This value divides {@link #DEFAULT_SPEED_PER_CHAR} to calculate the * final speed. Default value is {@code 100}. */ public static float MAX_SPEED_MODIFIER = 100.0f; /** * Defines how many chars can appear per frame. Use a value less than {@code 1} to disable this limit. Default value * is {@code -1}. */ public static int CHAR_LIMIT_PER_FRAME = -1; /** Default color for the {@code CLEARCOLOR} token. Can be overriden by {@link TypingLabel#getClearColor()}. */ public static Color DEFAULT_CLEAR_COLOR = new Color(Color.WHITE); /** Characters used to start and end tokens. Defaults to {@link TokenDelimiter#CURLY_BRACKETS}.*/ public static TokenDelimiter TOKEN_DELIMITER = TokenDelimiter.CURLY_BRACKETS; /** * Returns a map of characters and their respective interval multipliers, of which the interval to the next char * should be multiplied for. */ public static ObjectFloatMap INTERVAL_MULTIPLIERS_BY_CHAR = new ObjectFloatMap(); /** Map of global variables that affect all {@link TypingLabel} instances at once. */ public static final ObjectMap GLOBAL_VARS = new ObjectMap<>(); /** Map of start tokens and their effect classes. Internal use only. */ static final ObjectMap> EFFECT_START_TOKENS = new ObjectMap<>(); /** Map of end tokens and their effect classes. Internal use only. */ static final ObjectMap> EFFECT_END_TOKENS = new ObjectMap<>(); /** Whether or not effect tokens are dirty and need to be recalculated. */ static boolean dirtyEffectMaps = true; /** * Registers a new effect to TypingLabel. * * @param startTokenName Name of the token that starts the effect, such as WAVE. * @param endTokenName Name of the token that ends the effect, such as ENDWAVE. * @param effectClass Class of the effect, such as WaveEffect.class. */ public static void registerEffect(String startTokenName, String endTokenName, Class effectClass) { EFFECT_START_TOKENS.put(startTokenName.toUpperCase(), effectClass); EFFECT_END_TOKENS.put(endTokenName.toUpperCase(), effectClass); dirtyEffectMaps = true; } /** * Unregisters an effect from TypingLabel. * * @param startTokenName Name of the token that starts the effect, such as WAVE. * @param endTokenName Name of the token that ends the effect, such as ENDWAVE. */ public static void unregisterEffect(String startTokenName, String endTokenName) { EFFECT_START_TOKENS.remove(startTokenName.toUpperCase()); EFFECT_END_TOKENS.remove(endTokenName.toUpperCase()); } static { // Generate default char intervals INTERVAL_MULTIPLIERS_BY_CHAR.put(' ', 0.0f); INTERVAL_MULTIPLIERS_BY_CHAR.put(':', 1.5f); INTERVAL_MULTIPLIERS_BY_CHAR.put(',', 2.5f); INTERVAL_MULTIPLIERS_BY_CHAR.put('.', 2.5f); INTERVAL_MULTIPLIERS_BY_CHAR.put('!', 5.0f); INTERVAL_MULTIPLIERS_BY_CHAR.put('?', 5.0f); INTERVAL_MULTIPLIERS_BY_CHAR.put('\n', 20f); // Register default tokens registerEffect("EASE", "ENDEASE", EaseEffect.class); registerEffect("HANG", "ENDHANG", HangEffect.class); registerEffect("JUMP", "ENDJUMP", JumpEffect.class); registerEffect("SHAKE", "ENDSHAKE", ShakeEffect.class); registerEffect("SICK", "ENDSICK", SickEffect.class); registerEffect("SLIDE", "ENDSLIDE", SlideEffect.class); registerEffect("WAVE", "ENDWAVE", WaveEffect.class); registerEffect("WIND", "ENDWIND", WindEffect.class); registerEffect("RAINBOW", "ENDRAINBOW", RainbowEffect.class); registerEffect("GRADIENT", "ENDGRADIENT", GradientEffect.class); registerEffect("FADE", "ENDFADE", FadeEffect.class); registerEffect("BLINK", "ENDBLINK", BlinkEffect.class); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingGlyph.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.GlyphLayout.GlyphRun; /** Extension of {@link Glyph} with additional data exposed to the user. */ public class TypingGlyph extends Glyph { /** The color of the run this glyph belongs to, as an ABGR8888 int. */ public int runColor = 0xFFFFFFFF; /** Internal index associated with this glyph. Internal use only. Defaults to -1. */ int internalIndex = -1; /** Color of this glyph. If set to null, the run's color will be used. Defaults to null. */ public Color color = null; } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingLabel.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.GlyphLayout.GlyphRun; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.*; import com.badlogic.gdx.utils.StringBuilder; import com.badlogic.gdx.utils.ObjectMap.Entry; import com.badlogic.gdx.utils.reflect.ClassReflection; /** * An extension of {@link Label} that progressively shows the text as if it was being typed in real time, and allows the * use of tokens in the following format: {TOKEN=PARAMETER}. */ public class TypingLabel extends Label { /////////////////////// /// --- Members --- /// /////////////////////// // Collections private final ObjectMap variables = new ObjectMap(); protected final Array tokenEntries = new Array(); // Config private Color clearColor = new Color(TypingConfig.DEFAULT_CLEAR_COLOR); private final Array listeners = new Array<>(TypingListener.class); boolean forceMarkupColor = TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT; // Internal state private final StringBuilder originalText = new StringBuilder(); private final Array glyphCache = new Array(); private final IntArray glyphRunCapacities = new IntArray(); private final IntArray offsetCache = new IntArray(); private final IntArray layoutLineBreaks = new IntArray(); private final Array activeEffects = new Array(); private float textSpeed = TypingConfig.DEFAULT_SPEED_PER_CHAR; private float charCooldown = textSpeed; private int rawCharIndex = -2; // All chars, including color codes private int glyphCharIndex = -1; // Only renderable chars, excludes color codes private int glyphCharCompensation = 0; private int cachedGlyphCharIndex = -1; // Last glyphCharIndex sent to the cache private float lastLayoutX = 0; private float lastLayoutY = 0; private boolean parsed = false; private boolean paused = false; private boolean ended = false; private boolean skipping = false; private boolean ignoringEvents = false; private boolean ignoringEffects = false; private String defaultToken = ""; // Superclass mirroring boolean wrap; String ellipsis; float lastPrefHeight; boolean fontScaleChanged = false; private static final Color tempColor = new Color(); //////////////////////////// /// --- Constructors --- /// //////////////////////////// public TypingLabel(CharSequence text, LabelStyle style) { super(text, style); saveOriginalText(); } public TypingLabel(CharSequence text, Skin skin, String fontName, Color color) { super(text, skin, fontName, color); saveOriginalText(); } public TypingLabel(CharSequence text, Skin skin, String fontName, String colorName) { super(text, skin, fontName, colorName); saveOriginalText(); } public TypingLabel(CharSequence text, Skin skin, String styleName) { super(text, skin, styleName); saveOriginalText(); } public TypingLabel(CharSequence text, Skin skin) { super(text, skin); saveOriginalText(); } ///////////////////////////// /// --- Text Handling --- /// ///////////////////////////// /** * Modifies the text of this label. If the char progression is already running, it's highly recommended to use * {@link #restart(CharSequence)} instead. */ @Override public void setText(CharSequence newText) { this.setText(newText, true); } /** * Sets the text of this label. * * @param modifyOriginalText Flag determining if the original text should be modified as well. If {@code false}, * only the display text is changed while the original text is untouched. * @see #restart(CharSequence) */ protected void setText(CharSequence newText, boolean modifyOriginalText) { setText(newText, modifyOriginalText, true); } /** * Sets the text of this label. * * @param modifyOriginalText Flag determining if the original text should be modified as well. If {@code false}, * only the display text is changed while the original text is untouched. * @param restart Whether or not this label should restart. Defaults to true. * @see #restart(CharSequence) */ protected void setText(CharSequence newText, boolean modifyOriginalText, boolean restart) { final boolean hasEnded = this.hasEnded(); super.setText(newText); if(modifyOriginalText) saveOriginalText(); if(restart) { this.restart(); } if(hasEnded) { this.skipToTheEnd(true, false); } } /** Similar to {@link #getText()}, but returns the original text with all the tokens unchanged. */ public StringBuilder getOriginalText() { return originalText; } /** * Copies the content of {@link #getText()} to the {@link StringBuilder} containing the original text with all * tokens unchanged. */ protected void saveOriginalText() { originalText.setLength(0); originalText.insert(0, this.getText()); originalText.trimToSize(); } /** * Restores the original text with all tokens unchanged to this label. Make sure to call {@link #parseTokens()} to * parse the tokens again. */ protected void restoreOriginalText() { super.setText(originalText); this.parsed = false; } //////////////////////////// /// --- External API --- /// //////////////////////////// /** Returns the {@link TypingListener}s associated with this label. May be empty. */ public Array getTypingListeners() { return listeners; } /** Adds a {@link TypingListener} to this label. */ public void addTypingListener(TypingListener listener) { listeners.add(listener); } /** Clears all {@link TypingListener}s associated with this label. */ public void clearTypingListeners() { listeners.clear(); } /** * Returns a {@link Color} instance with the color to be used on {@code CLEARCOLOR} tokens. Modify this instance to * change the token color. Default value is specified by {@link TypingConfig}. * * @see TypingConfig#DEFAULT_CLEAR_COLOR */ public Color getClearColor() { return clearColor; } /** * Sets whether or not this instance should enable markup color by force. * * @see TypingConfig#FORCE_COLOR_MARKUP_BY_DEFAULT */ public void setForceMarkupColor(boolean forceMarkupColor) { this.forceMarkupColor = forceMarkupColor; } /** Returns the default token being used in this label. Defaults to empty string. */ public String getDefaultToken() { return defaultToken; } /** * Sets the default token being used in this label. This token will be used before the label's text, and after each * {RESET} call. Useful if you want a certain token to be active at all times without having to type it all the * time. */ public void setDefaultToken(String defaultToken) { this.defaultToken = defaultToken == null ? "" : defaultToken; this.parsed = false; } /** Parses all tokens of this label. Use this after setting the text and any variables that should be replaced. */ public void parseTokens() { this.setText(getDefaultToken() + getText(), false, false); Parser.parseTokens(this); parsed = true; } /** * Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too * long. Ignores all subsequent events by default. */ public void skipToTheEnd() { skipToTheEnd(true); } /** * Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too * long. * * @param ignoreEvents If {@code true}, skipped events won't be reported to the listener. */ public void skipToTheEnd(boolean ignoreEvents) { skipToTheEnd(ignoreEvents, false); } /** * Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too * long. * * @param ignoreEvents If {@code true}, skipped events won't be reported to the listener. * @param ignoreEffects If {@code true}, all text effects will be instantly cancelled. */ public void skipToTheEnd(boolean ignoreEvents, boolean ignoreEffects) { skipping = true; ignoringEvents = ignoreEvents; ignoringEffects = ignoreEffects; } /** * Cancels calls to {@link #skipToTheEnd()}. Useful if you need to restore the label's normal behavior at some event * after skipping. */ public void cancelSkipping() { if(skipping) { skipping = false; ignoringEvents = false; ignoringEffects = false; } } /** * Returns whether or not this label is currently skipping its typing progression all the way to the end. This is * only true if skipToTheEnd is called. */ public boolean isSkipping() { return skipping; } /** Returns whether or not this label is paused. */ public boolean isPaused() { return paused; } /** Pauses this label's character progression. */ public void pause() { paused = true; } /** Resumes this label's character progression. */ public void resume() { paused = false; } /** Returns whether or not this label's char progression has ended. */ public boolean hasEnded() { return ended; } /** * Restarts this label with the original text and starts the char progression right away. All tokens are * automatically parsed. */ public void restart() { restart(getOriginalText()); } /** * Restarts this label with the given text and starts the char progression right away. All tokens are automatically * parsed. */ public void restart(CharSequence newText) { // Reset cache collections GlyphUtils.freeAll(glyphCache); glyphCache.clear(); glyphRunCapacities.clear(); offsetCache.clear(); layoutLineBreaks.clear(); activeEffects.clear(); // Reset state textSpeed = TypingConfig.DEFAULT_SPEED_PER_CHAR; charCooldown = textSpeed; rawCharIndex = -2; glyphCharIndex = -1; glyphCharCompensation = 0; cachedGlyphCharIndex = -1; lastLayoutX = 0; lastLayoutY = 0; parsed = false; paused = false; ended = false; skipping = false; ignoringEvents = false; ignoringEffects = false; // Set new text this.setText(newText, true, false); invalidate(); // Parse tokens tokenEntries.clear(); parseTokens(); } /** Returns an {@link ObjectMap} with all the variable names and their respective replacement values. */ public ObjectMap getVariables() { return variables; } /** Registers a variable and its respective replacement value to this label. */ public void setVariable(String var, String value) { variables.put(var.toUpperCase(), value); } /** Registers a set of variables and their respective replacement values to this label. */ public void setVariables(ObjectMap variableMap) { this.variables.clear(); for(Entry entry : variableMap.entries()) { this.variables.put(entry.key.toUpperCase(), entry.value); } } /** Registers a set of variables and their respective replacement values to this label. */ public void setVariables(java.util.Map variableMap) { this.variables.clear(); for(java.util.Map.Entry entry : variableMap.entrySet()) { this.variables.put(entry.getKey().toUpperCase(), entry.getValue()); } } /** Removes all variables from this label. */ public void clearVariables() { this.variables.clear(); } ////////////////////////////////// /// --- Core Functionality --- /// ////////////////////////////////// @Override public void act(float delta) { super.act(delta); // Force token parsing if(!parsed) { parseTokens(); } // Update cooldown and process char progression if(skipping || (!ended && !paused)) { if(skipping || (charCooldown -= delta) < 0.0f) { processCharProgression(); } } // Restore glyph offsets if(activeEffects.size > 0) { for(int i = 0; i < glyphCache.size; i++) { TypingGlyph glyph = glyphCache.get(i); glyph.xoffset = offsetCache.get(i * 2); glyph.yoffset = offsetCache.get(i * 2 + 1); } } // Apply effects if(!ignoringEffects) { for(int i = activeEffects.size - 1; i >= 0; i--) { Effect effect = activeEffects.get(i); effect.update(delta); int start = effect.indexStart; int end = effect.indexEnd >= 0 ? effect.indexEnd : glyphCharIndex; // If effect is finished, remove it if(effect.isFinished()) { activeEffects.removeIndex(i); continue; } // Apply effect to glyph for(int j = Math.max(0, start); j <= glyphCharIndex && j <= end && j < glyphCache.size; j++) { TypingGlyph glyph = glyphCache.get(j); effect.apply(glyph, j, delta); } } } } /** Proccess char progression according to current cooldown and process all tokens in the current index. */ private void processCharProgression() { // Keep a counter of how many chars we're processing in this tick. int charCounter = 0; // Process chars while there's room for it while(skipping || charCooldown < 0.0f) { // Apply compensation to glyph index, if any if(glyphCharCompensation != 0) { if(glyphCharCompensation > 0) { glyphCharIndex++; glyphCharCompensation--; } else { glyphCharIndex--; glyphCharCompensation++; } // Increment cooldown and wait for it charCooldown += textSpeed; continue; } // Increase raw char index rawCharIndex++; // Get next character and calculate cooldown increment int safeIndex = MathUtils.clamp(rawCharIndex, 0, getText().length - 1); char primitiveChar = '\u0000'; // Null character by default if(getText().length > 0) { primitiveChar = getText().charAt(safeIndex); float intervalMultiplier = TypingConfig.INTERVAL_MULTIPLIERS_BY_CHAR.get(primitiveChar, 1); charCooldown += textSpeed * intervalMultiplier; } // If char progression is finished, or if text is empty, notify listener and abort routine int textLen = getText().length; if(textLen == 0 || rawCharIndex >= textLen) { if(!ended) { ended = true; skipping = false; for(TypingListener listener : listeners) { listener.end(); } } return; } // Detect layout line breaks boolean isLayoutLineBreak = false; if(layoutLineBreaks.contains(glyphCharIndex)) { layoutLineBreaks.removeValue(glyphCharIndex); isLayoutLineBreak = true; } // Increase glyph char index for all characters, except new lines. if(rawCharIndex >= 0 && primitiveChar != '\n' && primitiveChar != '\r' && !isLayoutLineBreak) glyphCharIndex++; // Process tokens according to the current index while(tokenEntries.size > 0 && tokenEntries.peek().index == rawCharIndex) { TokenEntry entry = tokenEntries.pop(); String token = entry.token; TokenCategory category = entry.category; // Process tokens switch(category) { case SPEED: { textSpeed = entry.floatValue; continue; } case WAIT: { glyphCharIndex--; glyphCharCompensation++; charCooldown += entry.floatValue; continue; } case SKIP: { if(entry.stringValue != null) { rawCharIndex += entry.stringValue.length(); } continue; } case EVENT: { if(!ignoringEvents) { for(TypingListener listener : listeners) { listener.event(entry.stringValue); } } continue; } case EFFECT_START: case EFFECT_END: { // Get effect class boolean isStart = category == TokenCategory.EFFECT_START; Class effectClass = isStart ? TypingConfig.EFFECT_START_TOKENS.get(token) : TypingConfig.EFFECT_END_TOKENS.get(token); // End all effects of the same type for(int i = 0; i < activeEffects.size; i++) { Effect effect = activeEffects.get(i); if(effect.indexEnd < 0) { if(ClassReflection.isAssignableFrom(effectClass, effect.getClass())) { effect.indexEnd = glyphCharIndex - 1; } } } // Create new effect if necessary if(isStart) { entry.effect.indexStart = glyphCharIndex; activeEffects.add(entry.effect); } } } } // Notify listener about char progression int nextIndex = MathUtils.clamp(rawCharIndex, 0, getText().length - 1); Character nextChar = nextIndex == 0 ? null : getText().charAt(nextIndex); if(nextChar != null) { for(TypingListener listener : listeners) { listener.onChar(nextChar); } } // Increment char counter charCounter++; // Break loop if this was our first glyph to prevent glyph issues. if(glyphCharIndex == -1) { charCooldown = textSpeed; break; } // Break loop if enough chars were processed charCounter++; int charLimit = TypingConfig.CHAR_LIMIT_PER_FRAME; if(!skipping && charLimit > 0 && charCounter > charLimit) { charCooldown = Math.max(charCooldown, textSpeed); break; } } } @Override public boolean remove() { GlyphUtils.freeAll(glyphCache); glyphCache.clear(); return super.remove(); } //////////////////////////////////// /// --- Superclass Mirroring --- /// //////////////////////////////////// @Override public BitmapFontCache getBitmapFontCache() { return super.getBitmapFontCache(); } @Override public void setEllipsis(String ellipsis) { // Mimics superclass but keeps an accessible reference super.setEllipsis(ellipsis); this.ellipsis = ellipsis; } @Override public void setEllipsis(boolean ellipsis) { // Mimics superclass but keeps an accessible reference super.setEllipsis(ellipsis); if(ellipsis) this.ellipsis = "..."; else this.ellipsis = null; } @Override public void setWrap(boolean wrap) { // Mimics superclass but keeps an accessible reference super.setWrap(wrap); this.wrap = wrap; } @Override public void setFontScale(float fontScale) { super.setFontScale(fontScale); this.fontScaleChanged = true; } @Override public void setFontScale(float fontScaleX, float fontScaleY) { super.setFontScale(fontScaleX, fontScaleY); this.fontScaleChanged = true; } @Override public void setFontScaleX(float fontScaleX) { super.setFontScaleX(fontScaleX); this.fontScaleChanged = true; } @Override public void setFontScaleY(float fontScaleY) { super.setFontScaleY(fontScaleY); this.fontScaleChanged = true; } @Override public void layout() { // --- SUPERCLASS IMPLEMENTATION --- BitmapFontCache cache = getBitmapFontCache(); StringBuilder text = getText(); GlyphLayout layout = super.getGlyphLayout(); int lineAlign = getLineAlign(); int labelAlign = getLabelAlign(); LabelStyle style = getStyle(); BitmapFont font = cache.getFont(); float oldScaleX = font.getScaleX(); float oldScaleY = font.getScaleY(); if(fontScaleChanged) font.getData().setScale(getFontScaleX(), getFontScaleY()); boolean wrap = this.wrap && ellipsis == null; if(wrap) { float prefHeight = getPrefHeight(); if(prefHeight != lastPrefHeight) { lastPrefHeight = prefHeight; invalidateHierarchy(); } } float width = getWidth(), height = getHeight(); Drawable background = style.background; float x = 0, y = 0; if(background != null) { x = background.getLeftWidth(); y = background.getBottomHeight(); width -= background.getLeftWidth() + background.getRightWidth(); height -= background.getBottomHeight() + background.getTopHeight(); } float textWidth, textHeight; if(wrap || text.indexOf("\n") != -1) { // If the text can span multiple lines, determine the text's actual size so it can be aligned within the label. layout.setText(font, text, 0, text.length, Color.WHITE, width, lineAlign, wrap, ellipsis); textWidth = layout.width; textHeight = layout.height; if((labelAlign & Align.left) == 0) { if((labelAlign & Align.right) != 0) x += width - textWidth; else x += (width - textWidth) / 2; } } else { textWidth = width; textHeight = font.getData().capHeight; } if((labelAlign & Align.top) != 0) { y += cache.getFont().isFlipped() ? 0 : height - textHeight; y += style.font.getDescent(); } else if((labelAlign & Align.bottom) != 0) { y += cache.getFont().isFlipped() ? height - textHeight : 0; y -= style.font.getDescent(); } else { y += (height - textHeight) / 2; } if(!cache.getFont().isFlipped()) y += textHeight; layout.setText(font, text, 0, text.length, Color.WHITE, textWidth, lineAlign, wrap, ellipsis); cache.setText(layout, x, y); if(fontScaleChanged) font.getData().setScale(oldScaleX, oldScaleY); // --- END OF SUPERCLASS IMPLEMENTATION --- // Store coordinates passed to BitmapFontCache lastLayoutX = x; lastLayoutY = y; // Perform cache layout operation, where the magic happens GlyphUtils.freeAll(glyphCache); glyphCache.clear(); layoutCache(); } /** * Reallocate glyph clones according to the updated {@link GlyphLayout}. This should only be called when the text or * the layout changes. */ private void layoutCache() { BitmapFontCache cache = getBitmapFontCache(); GlyphLayout layout = super.getGlyphLayout(); Array runs = layout.runs; IntArray colors = layout.colors; // Reset layout line breaks layoutLineBreaks.clear(); // Store GlyphRun sizes and count how many glyphs we have int glyphCount = 0; glyphRunCapacities.setSize(runs.size); for(int i = 0; i < runs.size; i++) { Array glyphs = runs.get(i).glyphs; glyphRunCapacities.set(i, glyphs.size); glyphCount += glyphs.size; } // Make sure our cache array can hold all glyphs if(glyphCache.size < glyphCount) { glyphCache.setSize(glyphCount); offsetCache.setSize(glyphCount * 2); } // Clone original glyphs with independent instances int index = -1; float lastY = 0; int colorIndex = 1; int currentColor = colors.size < 2 ? 0xFFFFFFFF : colors.get(1); int colorChange = colors.size < 4 ? glyphCount : colors.get(2); for(int i = 0; i < runs.size; i++) { GlyphRun run = runs.get(i); Array glyphs = run.glyphs; for(int j = 0; j < glyphs.size; j++) { // Detect and store layout line breaks if(!MathUtils.isEqual(run.y, lastY)) { lastY = run.y; layoutLineBreaks.add(index); } // Increment index index++; if(index >= colorChange && colorIndex + 2 < colors.size) { currentColor = colors.get(colorIndex += 2); colorChange = colors.size <= colorIndex + 1 ? glyphCount : colors.get(colorIndex + 1); } // Get original glyph Glyph original = glyphs.get(j); // Get clone glyph TypingGlyph clone = null; if(index < glyphCache.size) { clone = glyphCache.get(index); } if(clone == null) { clone = GlyphUtils.obtain(); glyphCache.set(index, clone); } GlyphUtils.clone(original, clone); clone.width *= getFontScaleX(); clone.height *= getFontScaleY(); clone.xoffset *= getFontScaleX(); clone.yoffset *= getFontScaleY(); clone.runColor = currentColor; // Store offset data offsetCache.set(index * 2, clone.xoffset); offsetCache.set(index * 2 + 1, clone.yoffset); // Replace glyph in original array glyphs.set(j, clone); } } // Remove exceeding glyphs from original array int glyphCountdown = glyphCharIndex; for(int i = 0; i < runs.size; i++) { Array glyphs = runs.get(i).glyphs; if(glyphs.size < glyphCountdown) { glyphCountdown -= glyphs.size; continue; } for(int j = 0; j < glyphs.size; j++) { if(glyphCountdown < 0) { glyphs.removeRange(j, glyphs.size - 1); break; } glyphCountdown--; } } // Pass new layout with custom glyphs to BitmapFontCache cache.setText(layout, lastLayoutX, lastLayoutY); } /** Adds cached glyphs to the active BitmapFontCache as the char index progresses. */ private void addMissingGlyphs() { // Add additional glyphs to layout array, if any int glyphLeft = glyphCharIndex - cachedGlyphCharIndex; if(glyphLeft < 1) return; // Get runs GlyphLayout layout = super.getGlyphLayout(); Array runs = layout.runs; // Iterate through GlyphRuns to find the next glyph spot int glyphCount = 0; for(int runIndex = 0; runIndex < glyphRunCapacities.size; runIndex++) { int runCapacity = glyphRunCapacities.get(runIndex); if((glyphCount + runCapacity) < cachedGlyphCharIndex) { glyphCount += runCapacity; continue; } // Get run and increase glyphCount up to its current size Array glyphs = runs.get(runIndex).glyphs; glyphCount += glyphs.size; // Next glyphs go here while(glyphLeft > 0) { // Skip run if this one is full int runSize = glyphs.size; if(runCapacity == runSize) { break; } // Put new glyph to this run cachedGlyphCharIndex++; TypingGlyph glyph = glyphCache.get(cachedGlyphCharIndex); glyphs.add(glyph); // Cache glyph's vertex index glyph.internalIndex = glyphCount; // Advance glyph count glyphCount++; glyphLeft--; } } } @Override public void draw(Batch batch, float parentAlpha) { super.validate(); addMissingGlyphs(); // Update cache with new glyphs BitmapFontCache bitmapFontCache = getBitmapFontCache(); getBitmapFontCache().setText(getGlyphLayout(), lastLayoutX, lastLayoutY); // --- SUPERCLASS IMPLEMENTATION --- // This section has to be copied from Label, since we can't call super.draw() without messing up our color. validate(); Color color = tempColor.set(getColor()); color.a *= parentAlpha; if (getStyle().background != null) { batch.setColor(color.r, color.g, color.b, color.a); getStyle().background.draw(batch, getX(), getY(), getWidth(), getHeight()); } if (getStyle().fontColor != null) color.mul(getStyle().fontColor); // --- END OF SUPERCLASS IMPLEMENTATION --- // Here we store color as its components, to avoid producing garbage and to allow modifying the local color. float r = color.r, g = color.g, b = color.b, a = color.a; for(TypingGlyph glyph : glyphCache) { if (glyph.internalIndex >= 0) { if (glyph.color != null) { // Unless we want to use a packed float, it's easiest to pass a Color object here, multiplying this // Label color (as its components) by the color of the individual glyph. bitmapFontCache.setColors( Color.toFloatBits(r * glyph.color.r, g * glyph.color.g, b * glyph.color.b, a * glyph.color.a), glyph.internalIndex, glyph.internalIndex + 1); } else if(a < 1f) { bitmapFontCache.setColors(color, glyph.internalIndex, glyph.internalIndex + 1); } } } // --- SUPERCLASS IMPLEMENTATION --- // This also replicates Label. Note that we don't call the super-method. bitmapFontCache.setPosition(getX(), getY()); bitmapFontCache.draw(batch); // --- END OF SUPERCLASS IMPLEMENTATION --- } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingListener.java ================================================ package com.rafaskoberg.gdx.typinglabel; /** Simple listener for label events. */ public interface TypingListener { /** * Called each time an {@code EVENT} token is processed. * * @param event Name of the event specified in the token. e.g. {EVENT=player_name} will have * player_name as argument. */ public void event(String event); /** Called when the char progression reaches the end. */ public void end(); /** * Called when variable tokens are replaced in text. This is an alternative method to deal with variables, other * than directly assigning replacement values to the label. Replacements returned by this method have priority over * direct values, unless {@code null} is returned. * * @param variable The variable name assigned to the {VAR} token. For example, in {VAR=townName}, * the variable will be townName * @return The replacement String, or {@code null} if this method should be ignored and the regular values should be * used instead. * @see TypingLabel#setVariable(String, String) * @see TypingLabel#setVariables(java.util.Map) * @see TypingLabel#setVariables(com.badlogic.gdx.utils.ObjectMap) */ public String replaceVariable(String variable); /** * Called when a new character is displayed. May be called many times per frame depending on the label * configurations and text speed. Useful to do a certain action each time a character is displayed, like playing a * sound effect. */ public void onChar(Character ch); } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/BlinkEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Blinks the entire text in two different colors at once, without interpolation. */ public class BlinkEffect extends Effect { private static final float DEFAULT_FREQUENCY = 1f; private Color color1 = null; // First color of the effect. private Color color2 = null; // Second color of the effect. private float frequency = 1; // How frequently the color pattern should move through the text. private float threshold = 0.5f; // Point to switch colors. public BlinkEffect(TypingLabel label, String[] params) { super(label); // Color 1 if(params.length > 0) { this.color1 = paramAsColor(params[0]); } // Color 2 if(params.length > 1) { this.color2 = paramAsColor(params[1]); } // Frequency if(params.length > 2) { this.frequency = paramAsFloat(params[2], 1); } // Threshold if(params.length > 3) { this.threshold = paramAsFloat(params[3], 0.5f); } // Validate parameters if(this.color1 == null) this.color1 = new Color(Color.WHITE); if(this.color2 == null) this.color2 = new Color(Color.WHITE); this.threshold = MathUtils.clamp(this.threshold, 0, 1); } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float frequencyMod = (1f / frequency) * DEFAULT_FREQUENCY; float progress = calculateProgress(frequencyMod); // Calculate color if(glyph.color == null) glyph.color = new Color(Color.WHITE); glyph.color.set(progress <= threshold ? color1 : color2); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/EaseEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.IntFloatMap; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Moves the text vertically easing it into the final position. Doesn't repeat itself. */ public class EaseEffect extends Effect { private static final float DEFAULT_DISTANCE = 0.15f; private static final float DEFAULT_INTENSITY = 0.075f; private float distance = 1; // How much of their height they should move private float intensity = 1; // How fast the glyphs should move private boolean elastic = false; // Whether or not the glyphs have an elastic movement private IntFloatMap timePassedByGlyphIndex = new IntFloatMap(); public EaseEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } //Intensity if(params.length > 1) { this.intensity = paramAsFloat(params[1], 1); } // Elastic if(params.length > 2) { this.elastic = paramAsBoolean(params[2]); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate real intensity float realIntensity = intensity * (elastic ? 3f : 1f) * DEFAULT_INTENSITY; // Calculate progress float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta); float progress = MathUtils.clamp(timePassed / realIntensity, 0, 1); // Calculate offset Interpolation interpolation = elastic ? Interpolation.swingOut : Interpolation.sine; float interpolatedValue = interpolation.apply(1, 0, progress); float y = getLineHeight() * distance * interpolatedValue * DEFAULT_DISTANCE; // Apply changes glyph.yoffset += y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/FadeEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.IntFloatMap; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Fades the text's color from between colors or alphas. Doesn't repeat itself. */ public class FadeEffect extends Effect { private Color color1 = null; // First color of the effect. private Color color2 = null; // Second color of the effect. private float alpha1 = 0; // First alpha of the effect, in case a color isn't provided. private float alpha2 = 1; // Second alpha of the effect, in case a color isn't provided. private float fadeDuration = 1; // Duration of the fade effect private IntFloatMap timePassedByGlyphIndex = new IntFloatMap(); public FadeEffect(TypingLabel label, String[] params) { super(label); // Color 1 or Alpha 1 if(params.length > 0) { this.color1 = paramAsColor(params[0]); if(this.color1 == null) { alpha1 = paramAsFloat(params[0], 0); } } // Color 2 or Alpha 2 if(params.length > 1) { this.color2 = paramAsColor(params[1]); if(this.color2 == null) { alpha2 = paramAsFloat(params[1], 1); } } // Fade duration if(params.length > 2) { this.fadeDuration = paramAsFloat(params[2], 1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta); float progress = MathUtils.clamp(timePassed / fadeDuration, 0, 1); // Create glyph color if necessary if(glyph.color == null) { glyph.color = new Color(Integer.reverseBytes(glyph.runColor)); } // Calculate initial color if(this.color1 == null) { glyph.color.a = MathUtils.lerp(glyph.color.a, this.alpha1, 1f - progress); } else { glyph.color.lerp(this.color1, 1f - progress); } // Calculate final color if(this.color2 == null) { glyph.color.a = MathUtils.lerp(glyph.color.a, this.alpha2, progress); } else { glyph.color.lerp(this.color2, progress); } } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/GradientEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.Color; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Tints the text in a gradient pattern. */ public class GradientEffect extends Effect { private static final float DEFAULT_DISTANCE = 0.975f; private static final float DEFAULT_FREQUENCY = 2f; private Color color1 = null; // First color of the gradient. private Color color2 = null; // Second color of the gradient. private float distance = 1; // How extensive the rainbow effect should be. private float frequency = 1; // How frequently the color pattern should move through the text. public GradientEffect(TypingLabel label, String[] params) { super(label); // Color 1 if(params.length > 0) { this.color1 = paramAsColor(params[0]); } // Color 2 if(params.length > 1) { this.color2 = paramAsColor(params[1]); } // Distance if(params.length > 2) { this.distance = paramAsFloat(params[2], 1); } // Frequency if(params.length > 3) { this.frequency = paramAsFloat(params[3], 1); } // Validate parameters if(this.color1 == null) this.color1 = new Color(Color.WHITE); if(this.color2 == null) this.color2 = new Color(Color.WHITE); } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float distanceMod = (1f / distance) * (1f - DEFAULT_DISTANCE); float frequencyMod = (1f / frequency) * DEFAULT_FREQUENCY; float progress = calculateProgress(frequencyMod, distanceMod * localIndex, true); // Calculate color if(glyph.color == null) glyph.color = new Color(Color.WHITE); glyph.color.set(color1).lerp(color2, progress); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/HangEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.IntFloatMap; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Hangs the text in midair and suddenly drops it. Doesn't repeat itself. */ public class HangEffect extends Effect { private static final float DEFAULT_DISTANCE = 0.7f; private static final float DEFAULT_INTENSITY = 1.5f; private float distance = 1; // How much of their height they should move private float intensity = 1; // How fast the glyphs should move private IntFloatMap timePassedByGlyphIndex = new IntFloatMap(); public HangEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Intensity if(params.length > 1) { this.intensity = paramAsFloat(params[1], 1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate real intensity float realIntensity = intensity * 1f * DEFAULT_INTENSITY; // Calculate progress float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta); float progress = MathUtils.clamp(timePassed / realIntensity, 0, 1); // Calculate offset float interpolation; float split = 0.7f; if(progress < split) { interpolation = Interpolation.pow3Out.apply(0, 1, progress / split); } else { interpolation = Interpolation.swing.apply(1, 0, (progress - split) / (1f - split)); } float distanceFactor = Interpolation.linear.apply(1.0f, 1.5f, progress); float y = getLineHeight() * distance * distanceFactor * interpolation * DEFAULT_DISTANCE; // Calculate fadeout float fadeout = calculateFadeout(); y *= fadeout; // Apply changes glyph.yoffset += y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/JumpEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.math.Interpolation; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Makes the text jumps and falls as if there was gravity. */ public class JumpEffect extends Effect { private static final float DEFAULT_FREQUENCY = 50f; private static final float DEFAULT_DISTANCE = 1.33f; private static final float DEFAULT_INTENSITY = 1f; private float distance = 1; // How much of their height they should move private float frequency = 1; // How frequently the wave pattern repeats private float intensity = 1; // How fast the glyphs should move public JumpEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Frequency if(params.length > 1) { this.frequency = paramAsFloat(params[1], 1); } // Intensity if(params.length > 2) { this.intensity = paramAsFloat(params[2], 1); } // Duration if(params.length > 3) { this.duration = paramAsFloat(params[3], -1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float progressModifier = (1f / intensity) * DEFAULT_INTENSITY; float normalFrequency = (1f / frequency) * DEFAULT_FREQUENCY; float progressOffset = localIndex / normalFrequency; float progress = calculateProgress(progressModifier, -progressOffset, false); // Calculate offset float interpolation = 0; float split = 0.2f; if(progress < split) { interpolation = Interpolation.pow2Out.apply(0, 1, progress / split); } else { interpolation = Interpolation.bounceOut.apply(1, 0, (progress - split) / (1f - split)); } float y = getLineHeight() * distance * interpolation * DEFAULT_DISTANCE; // Calculate fadeout float fadeout = calculateFadeout(); y *= fadeout; // Apply changes glyph.yoffset += y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/RainbowEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.Color; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; import com.rafaskoberg.gdx.typinglabel.utils.ColorUtils; /** Tints the text in a rainbow pattern. */ public class RainbowEffect extends Effect { private static final float DEFAULT_DISTANCE = 0.975f; private static final float DEFAULT_FREQUENCY = 2f; private float distance = 1; // How extensive the rainbow effect should be. private float frequency = 1; // How frequently the color pattern should move through the text. private float saturation = 1; // Color saturation private float brightness = 1; // Color brightness public RainbowEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Frequency if(params.length > 1) { this.frequency = paramAsFloat(params[1], 1); } // Saturation if(params.length > 2) { this.saturation = paramAsFloat(params[2], 1); } // Brightness if(params.length > 3) { this.brightness = paramAsFloat(params[3], 1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float distanceMod = (1f / distance) * (1f - DEFAULT_DISTANCE); float frequencyMod = (1f / frequency) * DEFAULT_FREQUENCY; float progress = calculateProgress(frequencyMod, distanceMod * localIndex, false); // Calculate color if(glyph.color == null) { glyph.color = new Color(Color.WHITE); } ColorUtils.HSVtoRGB(360f * progress, saturation * 100f, brightness * 100f, glyph.color); } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/ShakeEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.FloatArray; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Shakes the text in a random pattern. */ public class ShakeEffect extends Effect { private static final float DEFAULT_DISTANCE = 0.12f; private static final float DEFAULT_INTENSITY = 0.5f; private final FloatArray lastOffsets = new FloatArray(); private float distance = 1; // How far the glyphs should move private float intensity = 1; // How fast the glyphs should move public ShakeEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Intensity if(params.length > 1) { this.intensity = paramAsFloat(params[1], 1); } // Duration if(params.length > 2) { this.duration = paramAsFloat(params[2], -1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Make sure we can hold enough entries for the current index if(localIndex >= lastOffsets.size / 2) { lastOffsets.setSize(lastOffsets.size + 16); } // Get last offsets float lastX = lastOffsets.get(localIndex * 2); float lastY = lastOffsets.get(localIndex * 2 + 1); // Calculate new offsets float x = getLineHeight() * distance * MathUtils.random(-1, 1) * DEFAULT_DISTANCE; float y = getLineHeight() * distance * MathUtils.random(-1, 1) * DEFAULT_DISTANCE; // Apply intensity float normalIntensity = MathUtils.clamp(intensity * DEFAULT_INTENSITY, 0, 1); x = Interpolation.linear.apply(lastX, x, normalIntensity); y = Interpolation.linear.apply(lastY, y, normalIntensity); // Apply fadeout float fadeout = calculateFadeout(); x *= fadeout; y *= fadeout; x = Math.round(x); y = Math.round(y); // Store offsets for the next tick lastOffsets.set(localIndex * 2, x); lastOffsets.set(localIndex * 2 + 1, y); // Apply changes glyph.xoffset += x; glyph.yoffset += y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/SickEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.utils.IntArray; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Drips the text in a random pattern. */ public class SickEffect extends Effect { private static final float DEFAULT_FREQUENCY = 50f; private static final float DEFAULT_DISTANCE = .125f; private static final float DEFAULT_INTENSITY = 1f; public float distance = 1; // How far the glyphs should move public float intensity = 1; // How fast the glyphs should move private IntArray indices = new IntArray(); public SickEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Intensity if(params.length > 1) { this.intensity = paramAsFloat(params[1], 1); } // Duration if(params.length > 2) { this.duration = paramAsFloat(params[2], -1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float progressModifier = (1f / intensity) * DEFAULT_INTENSITY; float progressOffset = localIndex / DEFAULT_FREQUENCY; float progress = calculateProgress(progressModifier, -progressOffset, false); if(progress < .01f && Math.random() > .25f && !indices.contains(localIndex)) indices.add(localIndex); if(progress > .95f) indices.removeValue(localIndex); if(!indices.contains(localIndex) && !indices.contains(localIndex - 1) && !indices.contains(localIndex - 2) && !indices.contains(localIndex + 2) && !indices.contains(localIndex + 1)) return; // Calculate offset float interpolation = 0; float split = 0.5f; if(progress < split) { interpolation = Interpolation.pow2Out.apply(0, 1, progress / split); } else { interpolation = Interpolation.pow2In.apply(1, 0, (progress - split) / (1f - split)); } float y = getLineHeight() * distance * interpolation * DEFAULT_DISTANCE; if(indices.contains(localIndex)) y *= 2.15f; if(indices.contains(localIndex - 1) || indices.contains(localIndex + 1)) y *= 1.35f; // Calculate fadeout float fadeout = calculateFadeout(); y *= fadeout; // Apply changes glyph.yoffset -= y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/SlideEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.IntFloatMap; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Moves the text horizontally easing it into the final position. Doesn't repeat itself. */ public class SlideEffect extends Effect { private static final float DEFAULT_DISTANCE = 2f; private static final float DEFAULT_INTENSITY = 0.375f; private float distance = 1; // How much of their height they should move private float intensity = 1; // How fast the glyphs should move private boolean elastic = false; // Whether or not the glyphs have an elastic movement private IntFloatMap timePassedByGlyphIndex = new IntFloatMap(); public SlideEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Intensity if(params.length > 1) { this.intensity = paramAsFloat(params[1], 1); } // Elastic if(params.length > 2) { this.elastic = paramAsBoolean(params[2]); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate real intensity float realIntensity = intensity * (elastic ? 3f : 1f) * DEFAULT_INTENSITY; // Calculate progress float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta); float progress = MathUtils.clamp(timePassed / realIntensity, 0, 1); // Calculate offset Interpolation interpolation = elastic ? Interpolation.swingOut : Interpolation.sine; float interpolatedValue = interpolation.apply(1, 0, progress); float x = getLineHeight() * distance * interpolatedValue * DEFAULT_DISTANCE; // Apply changes glyph.xoffset += x; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/WaveEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.math.Interpolation; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; /** Moves the text vertically in a sine wave pattern. */ public class WaveEffect extends Effect { private static final float DEFAULT_FREQUENCY = 15f; private static final float DEFAULT_DISTANCE = 0.33f; private static final float DEFAULT_INTENSITY = 0.5f; private float distance = 1; // How much of their height they should move private float frequency = 1; // How frequently the wave pattern repeats private float intensity = 1; // How fast the glyphs should move public WaveEffect(TypingLabel label, String[] params) { super(label); // Distance if(params.length > 0) { this.distance = paramAsFloat(params[0], 1); } // Frequency if(params.length > 1) { this.frequency = paramAsFloat(params[1], 1); } // Intensity if(params.length > 2) { this.intensity = paramAsFloat(params[2], 1); } // Duration if(params.length > 3) { this.duration = paramAsFloat(params[3], -1); } } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float progressModifier = (1f / intensity) * DEFAULT_INTENSITY; float normalFrequency = (1f / frequency) * DEFAULT_FREQUENCY; float progressOffset = localIndex / normalFrequency; float progress = calculateProgress(progressModifier, progressOffset); // Calculate offset float y = getLineHeight() * distance * Interpolation.sine.apply(-1, 1, progress) * DEFAULT_DISTANCE; // Calculate fadeout float fadeout = calculateFadeout(); y *= fadeout; // Apply changes glyph.yoffset += y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/WindEffect.java ================================================ package com.rafaskoberg.gdx.typinglabel.effects; import com.rafaskoberg.gdx.typinglabel.Effect; import com.rafaskoberg.gdx.typinglabel.TypingGlyph; import com.rafaskoberg.gdx.typinglabel.TypingLabel; import com.rafaskoberg.gdx.typinglabel.utils.SimplexNoise; /** Moves the text in a wind pattern. */ public class WindEffect extends Effect { private static final float DEFAULT_SPACING = 10f; private static final float DEFAULT_DISTANCE = 0.33f; private static final float DEFAULT_INTENSITY = 0.375f; private static final float DISTANCE_X_RATIO = 1.5f; private static final float DISTANCE_Y_RATIO = 1.0f; private static final float IDEAL_DELTA = 60f; private SimplexNoise noise = new SimplexNoise(1, 0.5f, 1f); private float noiseCursorX = 0; private float noiseCursorY = 0; private float distanceX = 1; // How much of their line height glyphs should move in the X axis private float distanceY = 1; // How much of their line height glyphs should move in the Y axis private float spacing = 1; // How much space there should be between waves private float intensity = 1; // How strong the wind should be public WindEffect(TypingLabel label, String[] params) { super(label); // Distance X if(params.length > 0) { this.distanceX = paramAsFloat(params[0], 1); } // Distance Y if(params.length > 1) { this.distanceY = paramAsFloat(params[1], 1); } // Spacing if(params.length > 2) { this.spacing = paramAsFloat(params[2], 1); } // Intensity if(params.length > 3) { this.intensity = paramAsFloat(params[3], 1); } // Duration if(params.length > 4) { this.duration = paramAsFloat(params[4], -1); } } @Override public void update(float delta) { super.update(delta); // Update noise cursor float changeAmount = 0.1f * intensity * DEFAULT_INTENSITY * delta * IDEAL_DELTA; noiseCursorX += changeAmount; noiseCursorY += changeAmount; } @Override protected void onApply(TypingGlyph glyph, int localIndex, float delta) { // Calculate progress float progressModifier = DEFAULT_INTENSITY / intensity; float normalSpacing = DEFAULT_SPACING / spacing; float progressOffset = localIndex / normalSpacing; float progress = calculateProgress(progressModifier, progressOffset); // Calculate noise float indexOffset = localIndex * 0.05f * spacing; float noiseX = noise.getNoise(noiseCursorX + indexOffset, 0); float noiseY = noise.getNoise(0, noiseCursorY + indexOffset); // Calculate offset float lineHeight = getLineHeight(); float x = lineHeight * noiseX * progress * distanceX * DISTANCE_X_RATIO * DEFAULT_DISTANCE; float y = lineHeight * noiseY * progress * distanceY * DISTANCE_Y_RATIO * DEFAULT_DISTANCE; // Calculate fadeout float fadeout = calculateFadeout(); x *= fadeout; y *= fadeout; // Add flag effect to X offset x = Math.abs(x) * -Math.signum(distanceX); // Apply changes glyph.xoffset += x; glyph.yoffset += y; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/utils/ColorUtils.java ================================================ /* * Copyright 2014-2017 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Utility class borrowed from Vis-UI. */ package com.rafaskoberg.gdx.typinglabel.utils; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; /** * Utilities for converting between RGB and HSV color systems. * * @author Kotcrab * @since 0.6.0 */ public class ColorUtils { /** * Converts HSV to RGB * * @param h hue 0-360 * @param s saturation 0-100 * @param v value 0-100 * @param alpha 0-1 * @return RGB values in LibGDX {@link Color} class */ public static Color HSVtoRGB(float h, float s, float v, float alpha) { Color c = HSVtoRGB(h, s, v); c.a = alpha; return c; } /** * Converts HSV color system to RGB * * @param h hue 0-360 * @param s saturation 0-100 * @param v value 0-100 * @return RGB values in LibGDX {@link Color} class */ public static Color HSVtoRGB(float h, float s, float v) { Color c = new Color(1, 1, 1, 1); HSVtoRGB(h, s, v, c); return c; } /** * Converts HSV color system to RGB * * @param h hue 0-360 * @param s saturation 0-100 * @param v value 0-100 * @param targetColor color that result will be stored in * @return targetColor */ public static Color HSVtoRGB(float h, float s, float v, Color targetColor) { if(h >= 360) h = 359.999f; float r, g, b; int i; float f, p, q, t; h = (float) Math.max(0.0, Math.min(360.0, h)); s = (float) Math.max(0.0, Math.min(100.0, s)); v = (float) Math.max(0.0, Math.min(100.0, v)); s /= 100; v /= 100; h /= 60; i = MathUtils.floor(h); f = h - i; p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch(i) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; default: r = v; g = p; b = q; } targetColor.set(r, g, b, targetColor.a); return targetColor; } /** * Converts {@link Color} to HSV color system * * @return 3 element int array with hue (0-360), saturation (0-100) and value (0-100) */ public static int[] RGBtoHSV(Color c) { return RGBtoHSV(c.r, c.g, c.b); } /** * Converts RGB to HSV color system * * @param r red 0-1 * @param g green 0-1 * @param b blue 0-1 * @return 3 element int array with hue (0-360), saturation (0-100) and value (0-100) */ public static int[] RGBtoHSV(float r, float g, float b) { float h, s, v; float min, max, delta; min = Math.min(Math.min(r, g), b); max = Math.max(Math.max(r, g), b); v = max; delta = max - min; if(max != 0) s = delta / max; else { s = 0; h = 0; return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)}; } if(delta == 0) h = 0; else { if(r == max) h = (g - b) / delta; else if(g == max) h = 2 + (b - r) / delta; else h = 4 + (r - g) / delta; } h *= 60; if(h < 0) h += 360; s *= 100; v *= 100; return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)}; } } ================================================ FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/utils/SimplexNoise.java ================================================ package com.rafaskoberg.gdx.typinglabel.utils; import com.badlogic.gdx.math.MathUtils; /** * A speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. *

* Based on example code by Stefan Gustavson (stegu@itn.liu.se). Optimisations by Peter Eastman * (peastman@drizzle.stanford.edu). Better rank ordering method by Stefan Gustavson in 2012. *

* This could be speeded up even further, but it's useful as it is. *

* Version 2012-03-09 *

* This code was placed in the public domain by its original author, Stefan Gustavson. You may use it as you see fit, * but attribution is appreciated. */ public class SimplexNoise { // Simplex noise in 2D, 3D and 4D private static Grad[] grad3; private static Grad[] grad4; private static short[] p; private static short[] perm; private static short[] permMod12; static { grad3 = new Grad[]{ new Grad(1, 1, 0), new Grad(-1, 1, 0), new Grad(1, -1, 0), new Grad(-1, -1, 0), new Grad(1, 0, 1), new Grad(-1, 0, 1), new Grad(1, 0, -1), new Grad(-1, 0, -1), new Grad(0, 1, 1), new Grad(0, -1, 1), new Grad(0, 1, -1), new Grad(0, -1, -1) }; grad4 = new Grad[]{ new Grad(0, 1, 1, 1), new Grad(0, 1, 1, -1), new Grad(0, 1, -1, 1), new Grad(0, 1, -1, -1), new Grad(0, -1, 1, 1), new Grad(0, -1, 1, -1), new Grad(0, -1, -1, 1), new Grad(0, -1, -1, -1), new Grad(1, 0, 1, 1), new Grad(1, 0, 1, -1), new Grad(1, 0, -1, 1), new Grad(1, 0, -1, -1), new Grad(-1, 0, 1, 1), new Grad(-1, 0, 1, -1), new Grad(-1, 0, -1, 1), new Grad(-1, 0, -1, -1), new Grad(1, 1, 0, 1), new Grad(1, 1, 0, -1), new Grad(1, -1, 0, 1), new Grad(1, -1, 0, -1), new Grad(-1, 1, 0, 1), new Grad(-1, 1, 0, -1), new Grad(-1, -1, 0, 1), new Grad(-1, -1, 0, -1), new Grad(1, 1, 1, 0), new Grad(1, 1, -1, 0), new Grad(1, -1, 1, 0), new Grad(1, -1, -1, 0), new Grad(-1, 1, 1, 0), new Grad(-1, 1, -1, 0), new Grad(-1, -1, 1, 0), new Grad(-1, -1, -1, 0) }; p = new short[]{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }; // To remove the need for index wrapping, float the permutation table length perm = new short[512]; permMod12 = new short[512]; for(int i = 0; i < 512; i++) { perm[i] = p[i & 255]; permMod12[i] = (short) (perm[i] % 12); } } // Skewing and unskewing factors for 2, 3, and 4 dimensions private static final float F2 = (float) (0.5 * (Math.sqrt(3.0) - 1.0)); private static final float G2 = (float) ((3.0 - Math.sqrt(3.0)) / 6.0); private static final float F3 = (float) (1.0 / 3.0); private static final float G3 = (float) (1.0 / 6.0); private static final float F4 = (float) ((Math.sqrt(5.0) - 1.0) / 4.0); private static final float G4 = (float) ((5.0 - Math.sqrt(5.0)) / 20.0); // Instance variables for consistency and randomness private final int octaves; private final float roughness; private final float scale; private float offset; private int xCursor; private int yCursor; public SimplexNoise() { this(4, 1f, 1f); } public SimplexNoise(int octaves, float roughness, float scale) { this.octaves = octaves; this.roughness = roughness; this.scale = scale; generateNewOffset(); } public SimplexNoise(int octaves, float roughness, float scale, float offset) { this.octaves = octaves; this.roughness = roughness; this.scale = scale; this.offset = offset; } public void generateNewOffset() { this.offset = Short.MAX_VALUE * MathUtils.random(-1f, 1f); } public float getRawNoise(float x, float y) { return noise(x + offset, y + offset); } public float getRawNoise(float x, float y, float z) { return noise(x + offset, y + offset, z + offset); } public float getRawNoise(float x, float y, float z, float w) { return noise(x + offset, y + offset, z + offset, w + offset); } public float getNoise(float x, float y) { return octavedNoise(x + offset, y + offset, octaves, roughness, scale); } public float getNoise(float x, float y, float z) { return octavedNoise(x + offset, y + offset, z + offset, octaves, roughness, scale); } public float getNoise(float x, float y, float z, float w) { return octavedNoise(x + offset, y + offset, z + offset, w + offset, octaves, roughness, scale); } public float nextNoiseX() { return getNoise(xCursor++, 0); } public float nextNoiseY() { return getNoise(0, yCursor++); } // This method is a *lot* faster than using (int)Math.floor(x) private static int fastfloor(float x) { int xi = (int) x; return x < xi ? xi - 1 : xi; } private static float dot(Grad g, float x, float y) { return g.x * x + g.y * y; } private static float dot(Grad g, float x, float y, float z) { return g.x * x + g.y * y + g.z * z; } private static float dot(Grad g, float x, float y, float z, float w) { return g.x * x + g.y * y + g.z * z + g.w * w; } // 2D simplex noise public static float noise(float xin, float yin) { float n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in float s = (xin + yin) * F2; // Hairy factor for 2D int i = fastfloor(xin + s); int j = fastfloor(yin + s); float t = (i + j) * G2; float X0 = i - t; // Unskew the cell origin back to (x,y) space float Y0 = j - t; float x0 = xin - X0; // The x,y distances from the cell origin float y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if(x0 > y0) { i1 = 1; j1 = 0; } // lower triangle, XY order: (0,0)->(1,0)->(1,1) else { i1 = 0; j1 = 1; } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords float y1 = y0 - j1 + G2; float x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords float y2 = y0 - 1.0f + 2.0f * G2; // Work out the hashed gradient indices of the three simplex corners int ii = i & 255; int jj = j & 255; int gi0 = permMod12[ii + perm[jj]]; int gi1 = permMod12[ii + i1 + perm[jj + j1]]; int gi2 = permMod12[ii + 1 + perm[jj + 1]]; // Calculate the contribution from the three corners float t0 = 0.5f - x0 * x0 - y0 * y0; if(t0 < 0) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient } float t1 = 0.5f - x1 * x1 - y1 * y1; if(t1 < 0) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1); } float t2 = 0.5f - x2 * x2 - y2 * y2; if(t2 < 0) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 70.0f * (n0 + n1 + n2); } // 3D simplex noise public static float noise(float xin, float yin, float zin) { float n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in float s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D int i = fastfloor(xin + s); int j = fastfloor(yin + s); int k = fastfloor(zin + s); float t = (i + j + k) * G3; float X0 = i - t; // Unskew the cell origin back to (x,y,z) space float Y0 = j - t; float Z0 = k - t; float x0 = xin - X0; // The x,y,z distances from the cell origin float y0 = yin - Y0; float z0 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords if(x0 >= y0) { if(y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order else if(x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order } else { // x0 y0) rankx++; else ranky++; if(x0 > z0) rankx++; else rankz++; if(x0 > w0) rankx++; else rankw++; if(y0 > z0) ranky++; else rankz++; if(y0 > w0) ranky++; else rankw++; if(z0 > w0) rankz++; else rankw++; int i1, j1, k1, l1; // The integer offsets for the second simplex corner int i2, j2, k2, l2; // The integer offsets for the third simplex corner int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; j1 = ranky >= 3 ? 1 : 0; k1 = rankz >= 3 ? 1 : 0; l1 = rankw >= 3 ? 1 : 0; // Rank 2 denotes the second largest coordinate. i2 = rankx >= 2 ? 1 : 0; j2 = ranky >= 2 ? 1 : 0; k2 = rankz >= 2 ? 1 : 0; l2 = rankw >= 2 ? 1 : 0; // Rank 1 denotes the second smallest coordinate. i3 = rankx >= 1 ? 1 : 0; j3 = ranky >= 1 ? 1 : 0; k3 = rankz >= 1 ? 1 : 0; l3 = rankw >= 1 ? 1 : 0; // The fifth corner has all coordinate offsets = 1, so no need to compute that. float x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords float y1 = y0 - j1 + G4; float z1 = z0 - k1 + G4; float w1 = w0 - l1 + G4; float x2 = x0 - i2 + 2.0f * G4; // Offsets for third corner in (x,y,z,w) coords float y2 = y0 - j2 + 2.0f * G4; float z2 = z0 - k2 + 2.0f * G4; float w2 = w0 - l2 + 2.0f * G4; float x3 = x0 - i3 + 3.0f * G4; // Offsets for fourth corner in (x,y,z,w) coords float y3 = y0 - j3 + 3.0f * G4; float z3 = z0 - k3 + 3.0f * G4; float w3 = w0 - l3 + 3.0f * G4; float x4 = x0 - 1.0f + 4.0f * G4; // Offsets for last corner in (x,y,z,w) coords float y4 = y0 - 1.0f + 4.0f * G4; float z4 = z0 - 1.0f + 4.0f * G4; float w4 = w0 - 1.0f + 4.0f * G4; // Work out the hashed gradient indices of the five simplex corners int ii = i & 255; int jj = j & 255; int kk = k & 255; int ll = l & 255; int gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; int gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; int gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; int gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; int gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; // Calculate the contribution from the five corners float t0 = 0.6f - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; if(t0 < 0) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0); } float t1 = 0.6f - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; if(t1 < 0) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1); } float t2 = 0.6f - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; if(t2 < 0) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2); } float t3 = 0.6f - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; if(t3 < 0) n3 = 0.0f; else { t3 *= t3; n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3); } float t4 = 0.6f - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; if(t4 < 0) n4 = 0.0f; else { t4 *= t4; n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4); } // Sum up and scale the result to cover the range [-1,1] return 27.0f * (n0 + n1 + n2 + n3 + n4); } public static float octavedNoise(float xin, float yin, int octaves, float roughness, float scale) { float noiseSum = 0; float layerFrequency = scale; float layerWeight = 1; float weightSum = 0; for(int octave = 0; octave < octaves; octave++) { noiseSum += SimplexNoise.noise(xin * layerFrequency, yin * layerFrequency) * layerWeight; layerFrequency *= 2; weightSum += layerWeight; layerWeight *= roughness; } return noiseSum / weightSum; } public static float octavedNoise(float xin, float yin, float zin, int octaves, float roughness, float scale) { float noiseSum = 0; float layerFrequency = scale; float layerWeight = 1; float weightSum = 0; for(int octave = 0; octave < octaves; octave++) { noiseSum += noise(xin * layerFrequency, yin * layerFrequency, zin * layerFrequency) * layerWeight; layerFrequency *= 2; weightSum += layerWeight; layerWeight *= roughness; } return noiseSum / weightSum; } public static float octavedNoise(float xin, float yin, float zin, float win, int octaves, float roughness, float scale) { float noiseSum = 0; float layerFrequency = scale; float layerWeight = 1; float weightSum = 0; for(int octave = 0; octave < octaves; octave++) { noiseSum += noise(xin * layerFrequency, yin * layerFrequency, zin * layerFrequency, win * layerFrequency) * layerWeight; layerFrequency *= 2; weightSum += layerWeight; layerWeight *= roughness; } return noiseSum / weightSum; } // Inner class to speed upp gradient computations // (array access is a lot slower than member access) private static class Grad { float x, y, z, w; Grad(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } Grad(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } } } ================================================ FILE: src/main/resources/com/rafaskoberg/gdx/typinglabel/typinglabel.gwt.xml ================================================ ================================================ FILE: src/test/java/com/rafaskoberg/gdx/typinglabel/TypingLabelTest.java ================================================ package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Cell; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.viewport.ScreenViewport; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*; public class TypingLabelTest extends ApplicationAdapter { Skin skin; Stage stage; SpriteBatch batch; Table table; TypingLabel label; TypingLabel labelEvent; TextButton buttonPause; TextButton buttonResume; TextButton buttonRestart; TextButton buttonRebuild; TextButton buttonSkip; @Override public void create() { // Adjust typing config adjustTypingConfigs(); // Initiate batch, skin, and stage batch = new SpriteBatch(); skin = new Skin(Gdx.files.internal("uiskin.json")); skin.getAtlas().getTextures().iterator().next().setFilter(TextureFilter.Nearest, TextureFilter.Nearest); float scale = 1; skin.getFont("default-font").getData().setScale(scale); stage = new Stage(new ScreenViewport(), batch); Gdx.input.setInputProcessor(stage); // Create root table table = new Table(); stage.addActor(table); table.setFillParent(true); // Create main TypingLabel instance final String filename = "default.txt"; label = createTypingLabel(filename); // Create TypingLabel to show events labelEvent = new TypingLabel("", skin); labelEvent.setAlignment(Align.left, Align.center); labelEvent.pause(); labelEvent.setVisible(false); // Pause button buttonPause = new TextButton("Pause", skin); buttonPause.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { label.pause(); } }); // Resume button buttonResume = new TextButton("Resume", skin); buttonResume.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { label.resume(); } }); // Restart button buttonRestart = new TextButton("Restart", skin); buttonRestart.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { label.restart(); } }); // Rebuild button buttonRebuild = new TextButton("Rebuild", skin); buttonRebuild.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { adjustTypingConfigs(); Cell labelCell = table.getCell(label); label = createTypingLabel(filename); labelCell.setActor(label); } }); // Skip button buttonSkip = new TextButton("Skip", skin); buttonSkip.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { label.skipToTheEnd(); } }); // Populate table table.pad(50f); table.add(label).colspan(5).growX(); table.row(); table.add(labelEvent).colspan(5).align(Align.center); table.row().uniform().expand().growX().space(40).center(); table.add(buttonPause, buttonResume, buttonRestart, buttonSkip, buttonRebuild); table.pack(); } public void adjustTypingConfigs() { // Only allow two chars per frame TypingConfig.CHAR_LIMIT_PER_FRAME = 2; // Change color used by CLEARCOLOR token TypingConfig.DEFAULT_CLEAR_COLOR = Color.WHITE; // Force bitmap fonts to use color markup TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT = true; // Get token constants final char cOpen = TypingConfig.TOKEN_DELIMITER.open; final char cClose = TypingConfig.TOKEN_DELIMITER.close; // Create FIRE_WIND token as a global variable String fireWindToken = "{FASTER}{GRADIENT=ORANGE;DB6600;-0.5;5}{SLOWER}{WIND=2;4;0.5;0.5}".replace('{', cOpen).replace('}', cClose); TypingConfig.GLOBAL_VARS.put("FIRE_WIND", fireWindToken); } /** * Creates a TypingLabel instance with the default text file. */ public TypingLabel createTypingLabel() { return createTypingLabel("default.txt"); } /** * Creates a TypingLabel instance from the specified file. * * @param filename Name of the file under resources/text to be loaded. Must include the extension. */ public TypingLabel createTypingLabel(String filename) { // Get token constants final char cOpen = TypingConfig.TOKEN_DELIMITER.open; final char cClose = TypingConfig.TOKEN_DELIMITER.close; // Get text String text = Gdx.files.internal("text/" + filename).readString(); // Create label final TypingLabel label = new TypingLabel(text, skin); // Set default token String defaultToken = "{EASE}"; defaultToken = defaultToken.replace('{', cOpen).replace('}', cClose); label.setDefaultToken(defaultToken); // Make the label wrap to new lines, respecting the table's layout. label.setWrap(true); // Set variable replacements for the {VAR} and {IF} tokens label.setVariable("title", "curious human"); label.setVariable("gender", "f"); // Set an event listener for when the {EVENT} token is reached and for the char progression ends. label.addTypingListener(new TypingAdapter() { @Override public void event(String event) { System.out.println("Event: " + event); String eventLabelPrefix = "{FADE}{SLIDE=2;1;1}{FASTER}{COLOR=GRAY}Event:{WAIT=0.1}{COLOR=LIME} "; eventLabelPrefix = eventLabelPrefix.replace('{', cOpen).replace('}', cClose); labelEvent.restart(eventLabelPrefix + event); labelEvent.clearActions(); labelEvent.addAction( sequence( visible(true), alpha(0), alpha(1, 0.25f, Interpolation.pow2In), delay(0.5f), alpha(0, 2f, Interpolation.pow2) ) ); } @Override public void end() { System.out.println("End"); } }); // Finally parse tokens in the label text. label.parseTokens(); return label; } public void update(float delta) { stage.act(delta); } @Override public void render() { update(Gdx.graphics.getDeltaTime()); Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.draw(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void dispose() { stage.dispose(); skin.dispose(); } public static void main(String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "TypingLabel Test"; config.width = 720; config.height = 405; config.depth = 16; config.fullscreen = false; config.resizable = false; config.foregroundFPS = 60; config.backgroundFPS = 60; config.forceExit = false; new LwjglApplication(new TypingLabelTest(), config); } } ================================================ FILE: src/test/resources/arial18.fnt ================================================ info face="ArialMT" size=18 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=-2,-2 common lineHeight=22 base=17 scaleW=512 scaleH=512 pages=1 packed=0 page id=0 file="arial18.png" chars count=95 char id=10 x=0 y=0 width=0 height=0 xoffset=-2 yoffset=0 xadvance=5 page=0 chnl=0 char id=33 x=221 y=20 width=5 height=15 xoffset=-2 yoffset=3 xadvance=5 page=0 chnl=0 char id=34 x=450 y=20 width=8 height=7 xoffset=-2 yoffset=3 xadvance=6 page=0 chnl=0 char id=35 x=193 y=0 width=12 height=17 xoffset=-2 yoffset=2 xadvance=10 page=0 chnl=0 char id=36 x=73 y=0 width=12 height=19 xoffset=-2 yoffset=1 xadvance=10 page=0 chnl=0 char id=37 x=177 y=0 width=16 height=17 xoffset=-2 yoffset=2 xadvance=16 page=0 chnl=0 char id=38 x=205 y=0 width=14 height=17 xoffset=-2 yoffset=2 xadvance=12 page=0 chnl=0 char id=39 x=458 y=20 width=5 height=7 xoffset=-2 yoffset=3 xadvance=3 page=0 chnl=0 char id=40 x=0 y=0 width=7 height=20 xoffset=-2 yoffset=2 xadvance=6 page=0 chnl=0 char id=41 x=7 y=0 width=7 height=20 xoffset=-2 yoffset=2 xadvance=6 page=0 chnl=0 char id=42 x=441 y=20 width=9 height=9 xoffset=-2 yoffset=2 xadvance=7 page=0 chnl=0 char id=43 x=409 y=20 width=11 height=11 xoffset=-2 yoffset=5 xadvance=11 page=0 chnl=0 char id=44 x=463 y=20 width=5 height=7 xoffset=-2 yoffset=14 xadvance=5 page=0 chnl=0 char id=45 x=487 y=20 width=8 height=5 xoffset=-2 yoffset=10 xadvance=6 page=0 chnl=0 char id=46 x=495 y=20 width=5 height=4 xoffset=-2 yoffset=14 xadvance=5 page=0 chnl=0 char id=47 x=161 y=0 width=8 height=17 xoffset=-2 yoffset=2 xadvance=5 page=0 chnl=0 char id=48 x=383 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=49 x=177 y=20 width=8 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=50 x=185 y=20 width=12 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=51 x=323 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=52 x=197 y=20 width=12 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=53 x=335 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=54 x=347 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=55 x=209 y=20 width=12 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=56 x=359 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=57 x=371 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=58 x=380 y=20 width=5 height=12 xoffset=-2 yoffset=6 xadvance=5 page=0 chnl=0 char id=59 x=226 y=20 width=5 height=15 xoffset=-2 yoffset=6 xadvance=5 page=0 chnl=0 char id=60 x=385 y=20 width=12 height=12 xoffset=-2 yoffset=5 xadvance=11 page=0 chnl=0 char id=61 x=430 y=20 width=11 height=9 xoffset=-2 yoffset=6 xadvance=11 page=0 chnl=0 char id=62 x=397 y=20 width=12 height=12 xoffset=-2 yoffset=5 xadvance=11 page=0 chnl=0 char id=63 x=395 y=0 width=12 height=16 xoffset=-2 yoffset=2 xadvance=10 page=0 chnl=0 char id=64 x=35 y=0 width=20 height=20 xoffset=-2 yoffset=2 xadvance=18 page=0 chnl=0 char id=65 x=407 y=0 width=16 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=66 x=423 y=0 width=13 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=67 x=101 y=0 width=15 height=17 xoffset=-2 yoffset=2 xadvance=13 page=0 chnl=0 char id=68 x=436 y=0 width=14 height=15 xoffset=-2 yoffset=3 xadvance=13 page=0 chnl=0 char id=69 x=450 y=0 width=13 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=70 x=463 y=0 width=12 height=15 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=71 x=116 y=0 width=15 height=17 xoffset=-2 yoffset=2 xadvance=14 page=0 chnl=0 char id=72 x=475 y=0 width=13 height=15 xoffset=-2 yoffset=3 xadvance=13 page=0 chnl=0 char id=73 x=488 y=0 width=5 height=15 xoffset=-2 yoffset=3 xadvance=5 page=0 chnl=0 char id=74 x=219 y=0 width=10 height=16 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=75 x=493 y=0 width=13 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=76 x=0 y=20 width=11 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=77 x=11 y=20 width=15 height=15 xoffset=-2 yoffset=3 xadvance=15 page=0 chnl=0 char id=78 x=26 y=20 width=13 height=15 xoffset=-2 yoffset=3 xadvance=13 page=0 chnl=0 char id=79 x=131 y=0 width=16 height=17 xoffset=-2 yoffset=2 xadvance=14 page=0 chnl=0 char id=80 x=39 y=20 width=13 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=81 x=85 y=0 width=16 height=18 xoffset=-2 yoffset=2 xadvance=14 page=0 chnl=0 char id=82 x=52 y=20 width=14 height=15 xoffset=-2 yoffset=3 xadvance=13 page=0 chnl=0 char id=83 x=147 y=0 width=14 height=17 xoffset=-2 yoffset=2 xadvance=12 page=0 chnl=0 char id=84 x=66 y=20 width=13 height=15 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=85 x=229 y=0 width=13 height=16 xoffset=-2 yoffset=3 xadvance=13 page=0 chnl=0 char id=86 x=79 y=20 width=14 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=87 x=93 y=20 width=19 height=15 xoffset=-2 yoffset=3 xadvance=17 page=0 chnl=0 char id=88 x=112 y=20 width=14 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=89 x=126 y=20 width=14 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=90 x=140 y=20 width=13 height=15 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=91 x=61 y=0 width=6 height=19 xoffset=-2 yoffset=3 xadvance=5 page=0 chnl=0 char id=92 x=169 y=0 width=8 height=17 xoffset=-2 yoffset=2 xadvance=5 page=0 chnl=0 char id=93 x=67 y=0 width=6 height=19 xoffset=-2 yoffset=3 xadvance=5 page=0 chnl=0 char id=94 x=420 y=20 width=10 height=10 xoffset=-2 yoffset=2 xadvance=8 page=0 chnl=0 char id=95 x=0 y=35 width=14 height=4 xoffset=-2 yoffset=18 xadvance=10 page=0 chnl=0 char id=96 x=480 y=20 width=7 height=5 xoffset=-2 yoffset=3 xadvance=6 page=0 chnl=0 char id=97 x=231 y=20 width=12 height=13 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=98 x=242 y=0 width=11 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=99 x=243 y=20 width=11 height=13 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=100 x=253 y=0 width=11 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=101 x=254 y=20 width=12 height=13 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=102 x=264 y=0 width=8 height=16 xoffset=-2 yoffset=2 xadvance=5 page=0 chnl=0 char id=103 x=272 y=0 width=11 height=16 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=104 x=153 y=20 width=10 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=105 x=506 y=0 width=4 height=15 xoffset=-2 yoffset=3 xadvance=4 page=0 chnl=0 char id=106 x=55 y=0 width=6 height=19 xoffset=-2 yoffset=3 xadvance=4 page=0 chnl=0 char id=107 x=163 y=20 width=10 height=15 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=108 x=173 y=20 width=4 height=15 xoffset=-2 yoffset=3 xadvance=4 page=0 chnl=0 char id=109 x=299 y=20 width=15 height=12 xoffset=-2 yoffset=6 xadvance=15 page=0 chnl=0 char id=110 x=314 y=20 width=10 height=12 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=111 x=266 y=20 width=12 height=13 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=112 x=283 y=0 width=11 height=16 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=113 x=294 y=0 width=11 height=16 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=114 x=324 y=20 width=8 height=12 xoffset=-2 yoffset=6 xadvance=6 page=0 chnl=0 char id=115 x=278 y=20 width=11 height=13 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=116 x=305 y=0 width=7 height=16 xoffset=-2 yoffset=3 xadvance=5 page=0 chnl=0 char id=117 x=289 y=20 width=10 height=13 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=118 x=332 y=20 width=11 height=12 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=119 x=343 y=20 width=15 height=12 xoffset=-2 yoffset=6 xadvance=13 page=0 chnl=0 char id=120 x=358 y=20 width=11 height=12 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=121 x=312 y=0 width=11 height=16 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=122 x=369 y=20 width=11 height=12 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=123 x=14 y=0 width=8 height=20 xoffset=-2 yoffset=2 xadvance=6 page=0 chnl=0 char id=124 x=30 y=0 width=5 height=20 xoffset=-2 yoffset=2 xadvance=5 page=0 chnl=0 char id=125 x=22 y=0 width=8 height=20 xoffset=-2 yoffset=2 xadvance=6 page=0 chnl=0 char id=126 x=468 y=20 width=12 height=6 xoffset=-2 yoffset=8 xadvance=11 page=0 chnl=0 ================================================ FILE: src/test/resources/default.fnt ================================================ info face="Droid Sans" size=17 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 common lineHeight=20 base=18 scaleW=256 scaleH=128 pages=1 packed=0 page id=0 file="default.png" chars count=96 char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=16 xadvance=4 page=0 chnl=0 char id=124 x=0 y=0 width=6 height=20 xoffset=1 yoffset=3 xadvance=9 page=0 chnl=0 char id=106 x=6 y=0 width=9 height=20 xoffset=-4 yoffset=3 xadvance=4 page=0 chnl=0 char id=81 x=15 y=0 width=15 height=19 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=74 x=30 y=0 width=11 height=19 xoffset=-5 yoffset=3 xadvance=4 page=0 chnl=0 char id=125 x=41 y=0 width=10 height=18 xoffset=-3 yoffset=3 xadvance=6 page=0 chnl=0 char id=123 x=51 y=0 width=10 height=18 xoffset=-3 yoffset=3 xadvance=6 page=0 chnl=0 char id=93 x=61 y=0 width=8 height=18 xoffset=-3 yoffset=3 xadvance=5 page=0 chnl=0 char id=91 x=69 y=0 width=8 height=18 xoffset=-2 yoffset=3 xadvance=5 page=0 chnl=0 char id=41 x=77 y=0 width=9 height=18 xoffset=-3 yoffset=3 xadvance=5 page=0 chnl=0 char id=40 x=86 y=0 width=9 height=18 xoffset=-3 yoffset=3 xadvance=5 page=0 chnl=0 char id=64 x=95 y=0 width=18 height=17 xoffset=-3 yoffset=3 xadvance=14 page=0 chnl=0 char id=121 x=113 y=0 width=13 height=17 xoffset=-3 yoffset=6 xadvance=8 page=0 chnl=0 char id=113 x=126 y=0 width=13 height=17 xoffset=-3 yoffset=6 xadvance=9 page=0 chnl=0 char id=112 x=139 y=0 width=13 height=17 xoffset=-2 yoffset=6 xadvance=9 page=0 chnl=0 char id=103 x=152 y=0 width=13 height=17 xoffset=-3 yoffset=6 xadvance=8 page=0 chnl=0 char id=38 x=165 y=0 width=16 height=16 xoffset=-3 yoffset=3 xadvance=11 page=0 chnl=0 char id=37 x=181 y=0 width=18 height=16 xoffset=-3 yoffset=3 xadvance=14 page=0 chnl=0 char id=36 x=199 y=0 width=12 height=16 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=63 x=211 y=0 width=11 height=16 xoffset=-3 yoffset=3 xadvance=7 page=0 chnl=0 char id=33 x=222 y=0 width=7 height=16 xoffset=-2 yoffset=3 xadvance=4 page=0 chnl=0 char id=48 x=229 y=0 width=13 height=16 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=57 x=242 y=0 width=13 height=16 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=56 x=0 y=20 width=13 height=16 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=54 x=13 y=20 width=13 height=16 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=53 x=26 y=20 width=12 height=16 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=51 x=38 y=20 width=13 height=16 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=100 x=51 y=20 width=13 height=16 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=98 x=64 y=20 width=13 height=16 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=85 x=77 y=20 width=14 height=16 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=83 x=91 y=20 width=13 height=16 xoffset=-3 yoffset=3 xadvance=8 page=0 chnl=0 char id=79 x=104 y=20 width=15 height=16 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=71 x=119 y=20 width=14 height=16 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=67 x=133 y=20 width=13 height=16 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=127 x=146 y=20 width=12 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=35 x=158 y=20 width=15 height=15 xoffset=-3 yoffset=3 xadvance=10 page=0 chnl=0 char id=92 x=173 y=20 width=11 height=15 xoffset=-3 yoffset=3 xadvance=6 page=0 chnl=0 char id=47 x=184 y=20 width=11 height=15 xoffset=-3 yoffset=3 xadvance=6 page=0 chnl=0 char id=59 x=195 y=20 width=8 height=15 xoffset=-3 yoffset=6 xadvance=4 page=0 chnl=0 char id=55 x=203 y=20 width=13 height=15 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=52 x=216 y=20 width=14 height=15 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=50 x=230 y=20 width=13 height=15 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=49 x=243 y=20 width=9 height=15 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=116 x=0 y=36 width=10 height=15 xoffset=-3 yoffset=4 xadvance=5 page=0 chnl=0 char id=108 x=10 y=36 width=6 height=15 xoffset=-2 yoffset=3 xadvance=4 page=0 chnl=0 char id=107 x=16 y=36 width=12 height=15 xoffset=-2 yoffset=3 xadvance=8 page=0 chnl=0 char id=105 x=28 y=36 width=7 height=15 xoffset=-2 yoffset=3 xadvance=4 page=0 chnl=0 char id=104 x=35 y=36 width=12 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=102 x=47 y=36 width=11 height=15 xoffset=-3 yoffset=3 xadvance=5 page=0 chnl=0 char id=90 x=58 y=36 width=13 height=15 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=89 x=71 y=36 width=13 height=15 xoffset=-3 yoffset=3 xadvance=8 page=0 chnl=0 char id=88 x=84 y=36 width=14 height=15 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=87 x=98 y=36 width=19 height=15 xoffset=-3 yoffset=3 xadvance=15 page=0 chnl=0 char id=86 x=117 y=36 width=14 height=15 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=84 x=131 y=36 width=13 height=15 xoffset=-3 yoffset=3 xadvance=8 page=0 chnl=0 char id=82 x=144 y=36 width=13 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=80 x=157 y=36 width=12 height=15 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=78 x=169 y=36 width=14 height=15 xoffset=-2 yoffset=3 xadvance=12 page=0 chnl=0 char id=77 x=183 y=36 width=17 height=15 xoffset=-2 yoffset=3 xadvance=14 page=0 chnl=0 char id=76 x=200 y=36 width=11 height=15 xoffset=-2 yoffset=3 xadvance=8 page=0 chnl=0 char id=75 x=211 y=36 width=13 height=15 xoffset=-2 yoffset=3 xadvance=9 page=0 chnl=0 char id=73 x=224 y=36 width=10 height=15 xoffset=-3 yoffset=3 xadvance=5 page=0 chnl=0 char id=72 x=234 y=36 width=14 height=15 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=70 x=0 y=51 width=11 height=15 xoffset=-2 yoffset=3 xadvance=8 page=0 chnl=0 char id=69 x=11 y=51 width=11 height=15 xoffset=-2 yoffset=3 xadvance=8 page=0 chnl=0 char id=68 x=22 y=51 width=14 height=15 xoffset=-2 yoffset=3 xadvance=11 page=0 chnl=0 char id=66 x=36 y=51 width=13 height=15 xoffset=-2 yoffset=3 xadvance=10 page=0 chnl=0 char id=65 x=49 y=51 width=15 height=15 xoffset=-3 yoffset=3 xadvance=10 page=0 chnl=0 char id=58 x=64 y=51 width=7 height=13 xoffset=-2 yoffset=6 xadvance=4 page=0 chnl=0 char id=117 x=71 y=51 width=12 height=13 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=115 x=83 y=51 width=11 height=13 xoffset=-3 yoffset=6 xadvance=7 page=0 chnl=0 char id=111 x=94 y=51 width=13 height=13 xoffset=-3 yoffset=6 xadvance=9 page=0 chnl=0 char id=101 x=107 y=51 width=13 height=13 xoffset=-3 yoffset=6 xadvance=9 page=0 chnl=0 char id=99 x=120 y=51 width=12 height=13 xoffset=-3 yoffset=6 xadvance=7 page=0 chnl=0 char id=97 x=132 y=51 width=12 height=13 xoffset=-3 yoffset=6 xadvance=9 page=0 chnl=0 char id=60 x=144 y=51 width=13 height=12 xoffset=-3 yoffset=5 xadvance=9 page=0 chnl=0 char id=122 x=157 y=51 width=11 height=12 xoffset=-3 yoffset=6 xadvance=7 page=0 chnl=0 char id=120 x=168 y=51 width=13 height=12 xoffset=-3 yoffset=6 xadvance=8 page=0 chnl=0 char id=119 x=181 y=51 width=17 height=12 xoffset=-3 yoffset=6 xadvance=12 page=0 chnl=0 char id=118 x=198 y=51 width=13 height=12 xoffset=-3 yoffset=6 xadvance=8 page=0 chnl=0 char id=114 x=211 y=51 width=10 height=12 xoffset=-2 yoffset=6 xadvance=6 page=0 chnl=0 char id=110 x=221 y=51 width=12 height=12 xoffset=-2 yoffset=6 xadvance=10 page=0 chnl=0 char id=109 x=233 y=51 width=17 height=12 xoffset=-2 yoffset=6 xadvance=15 page=0 chnl=0 char id=94 x=0 y=66 width=13 height=11 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=62 x=13 y=66 width=13 height=11 xoffset=-3 yoffset=5 xadvance=9 page=0 chnl=0 char id=42 x=26 y=66 width=13 height=10 xoffset=-3 yoffset=3 xadvance=9 page=0 chnl=0 char id=43 x=39 y=66 width=13 height=10 xoffset=-3 yoffset=6 xadvance=9 page=0 chnl=0 char id=61 x=52 y=66 width=13 height=8 xoffset=-3 yoffset=7 xadvance=9 page=0 chnl=0 char id=39 x=65 y=66 width=6 height=8 xoffset=-2 yoffset=3 xadvance=3 page=0 chnl=0 char id=34 x=71 y=66 width=9 height=8 xoffset=-2 yoffset=3 xadvance=6 page=0 chnl=0 char id=44 x=80 y=66 width=8 height=7 xoffset=-3 yoffset=14 xadvance=4 page=0 chnl=0 char id=126 x=88 y=66 width=13 height=6 xoffset=-3 yoffset=8 xadvance=9 page=0 chnl=0 char id=46 x=101 y=66 width=7 height=6 xoffset=-2 yoffset=13 xadvance=4 page=0 chnl=0 char id=96 x=108 y=66 width=8 height=6 xoffset=0 yoffset=2 xadvance=9 page=0 chnl=0 char id=45 x=116 y=66 width=9 height=5 xoffset=-3 yoffset=10 xadvance=5 page=0 chnl=0 char id=95 x=125 y=66 width=13 height=4 xoffset=-4 yoffset=17 xadvance=6 page=0 chnl=0 kernings count=-1 ================================================ FILE: src/test/resources/text/colors.txt ================================================ {COLOR=RED}#{COLOR=BLUE}={COLOR=GREEN}#{COLOR=WHITE}={RESET} {COLOR=RED}##{COLOR=BLUE}=={COLOR=GREEN}##{COLOR=WHITE}=={RESET} {COLOR=RED}##########{COLOR=BLUE}=========={COLOR=GREEN}##########{COLOR=WHITE}=========={RESET} [RED]##########[BLUE]==========[GREEN]##########[WHITE]==========[] {GRADIENT=FF0000;FFC300}##########{ENDGRADIENT}{GRADIENT=00FF00;C3FF00}=========={ENDGRADIENT}{GRADIENT=0000FF;C300FF}##########{ENDGRADIENT}{GRADIENT=FFFFFF;FFC3FF}=========={RESET} ================================================ FILE: src/test/resources/text/default.txt ================================================ {WAIT=1}{SLOWER}{GRADIENT=FF70F1;FFC300;-0.5;5}{EASE=-8;2;1}Welcome,{WAIT} {VAR=title}!{ENDEASE}{FAST} {RESET}{HANG=0.7}This is a simple test{ENDHANG} to show you{GRADIENT=27C1F5;2776E7;-0.5;5} {JUMP}how to make dialogues {SLOW}fun again! {ENDJUMP}{WAIT}{ENDGRADIENT} {NORMAL}{CLEARCOLOR}{SICK} With this library{ENDSICK} you can control the flow of the text with {BLINK=FF6BF3;FF0582;3}tokens{ENDBLINK},{WAIT=0.7}{SPEED=2.50}{COLOR=#84DD60} making the text go {SHAKE=1;1;3}really fast{ENDSHAKE}{WAIT=0.5} {SPEED=0.25}{COLOR=#A6E22D}{WAVE=0.66}or extremely slow.{ENDWAVE}{RESET} You can also wait for a {EASE=-15;2;1}second{ENDEASE}{WAIT=1} {EASE=15;8;1}{COLOR=#E6DB74}or two{CLEARCOLOR}{ENDEASE}{WAIT=2},{RAINBOW=1;1;0.7} just to catch an event in code{EVENT=example}!{WAIT} {ENDHANG}{ENDRAINBOW}{NORMAL} {VAR=FIRE_WIND}Imagine the possibilities! =D {RESET} ================================================ FILE: src/test/resources/text/gender_pronouns.txt ================================================ - Hi {VAR=title}, have you seen {IF=GENDER;f=her;m=him;t=them} today? - I saw {IF=gender;f=her;m=him;t=them} this morning. {IF=GENDER;f=She;m=He;t=They} seemed well! ================================================ FILE: src/test/resources/text/gender_pronouns_defaults.txt ================================================ - Have you seen {IF=GENDER}? - Have you seen {IF=GENDER;}? - Have you seen {IF=GENDER;Mewtwo}? - Have you seen {IF=GENDER;f=;m=;t=}? - Have you seen {IF=GENDER;f:Charmander}? - Have you seen {IF=GENDER;a=;}? - Have you seen {IF=GENDER;a=;=}? ================================================ FILE: src/test/resources/uiskin.atlas ================================================ uiskin.png size: 256,128 format: RGBA8888 filter: Linear,Linear repeat: none check-off rotate: false xy: 11, 5 size: 14, 14 orig: 14, 14 offset: 0, 0 index: -1 textfield rotate: false xy: 11, 5 size: 14, 14 split: 3, 3, 3, 3 orig: 14, 14 offset: 0, 0 index: -1 check-on rotate: false xy: 125, 35 size: 14, 14 orig: 14, 14 offset: 0, 0 index: -1 cursor rotate: false xy: 23, 1 size: 3, 3 split: 1, 1, 1, 1 orig: 3, 3 offset: 0, 0 index: -1 default rotate: false xy: 1, 50 size: 254, 77 orig: 254, 77 offset: 0, 0 index: -1 default-pane rotate: false xy: 11, 1 size: 5, 3 split: 1, 1, 1, 1 orig: 5, 3 offset: 0, 0 index: -1 default-rect-pad rotate: false xy: 11, 1 size: 5, 3 split: 1, 1, 1, 1 orig: 5, 3 offset: 0, 0 index: -1 default-pane-noborder rotate: false xy: 170, 44 size: 1, 1 split: 0, 0, 0, 0 orig: 1, 1 offset: 0, 0 index: -1 default-rect rotate: false xy: 38, 25 size: 3, 3 split: 1, 1, 1, 1 orig: 3, 3 offset: 0, 0 index: -1 default-rect-down rotate: false xy: 170, 46 size: 3, 3 split: 1, 1, 1, 1 orig: 3, 3 offset: 0, 0 index: -1 default-round rotate: false xy: 112, 29 size: 12, 20 split: 5, 5, 5, 4 pad: 4, 4, 1, 1 orig: 12, 20 offset: 0, 0 index: -1 default-round-down rotate: false xy: 99, 29 size: 12, 20 split: 5, 5, 5, 4 pad: 4, 4, 1, 1 orig: 12, 20 offset: 0, 0 index: -1 default-round-large rotate: false xy: 57, 29 size: 20, 20 split: 5, 5, 5, 4 orig: 20, 20 offset: 0, 0 index: -1 default-scroll rotate: false xy: 78, 29 size: 20, 20 split: 2, 2, 2, 2 orig: 20, 20 offset: 0, 0 index: -1 default-select rotate: false xy: 29, 29 size: 27, 20 split: 4, 14, 4, 4 orig: 27, 20 offset: 0, 0 index: -1 default-select-selection rotate: false xy: 26, 16 size: 3, 3 split: 1, 1, 1, 1 orig: 3, 3 offset: 0, 0 index: -1 default-slider rotate: false xy: 29, 20 size: 8, 8 split: 2, 2, 2, 2 orig: 8, 8 offset: 0, 0 index: -1 default-slider-knob rotate: false xy: 1, 1 size: 9, 18 orig: 9, 18 offset: 0, 0 index: -1 default-splitpane rotate: false xy: 17, 1 size: 5, 3 split: 0, 5, 0, 0 orig: 5, 3 offset: 0, 0 index: -1 default-splitpane-vertical rotate: false xy: 125, 29 size: 3, 5 split: 0, 0, 0, 5 orig: 3, 5 offset: 0, 0 index: -1 default-window rotate: false xy: 1, 20 size: 27, 29 split: 4, 3, 20, 3 orig: 27, 29 offset: 0, 0 index: -1 selection rotate: false xy: 174, 48 size: 1, 1 orig: 1, 1 offset: 0, 0 index: -1 tree-minus rotate: false xy: 140, 35 size: 14, 14 orig: 14, 14 offset: 0, 0 index: -1 tree-plus rotate: false xy: 155, 35 size: 14, 14 orig: 14, 14 offset: 0, 0 index: -1 white rotate: false xy: 129, 31 size: 3, 3 orig: 3, 3 offset: 0, 0 index: -1 ================================================ FILE: src/test/resources/uiskin.json ================================================ { com.badlogic.gdx.graphics.g2d.BitmapFont: { default-font: { file: arial18.fnt } }, com.badlogic.gdx.graphics.Color: { green: { a: 1, b: 0, g: 1, r: 0 }, white: { a: 1, b: 1, g: 1, r: 1 }, red: { a: 1, b: 0, g: 0, r: 1 }, black: { a: 1, b: 0, g: 0, r: 0 }, }, com.badlogic.gdx.scenes.scene2d.ui.Skin$TintedDrawable: { dialogDim: { name: white, color: { r: 0, g: 0, b: 0, a: 0.45 } }, }, com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle: { default: { down: default-round-down, up: default-round }, toggle: { down: default-round-down, checked: default-round-down, up: default-round } }, com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: { default: { down: default-round-down, up: default-round, font: default-font, fontColor: white }, toggle: { down: default-round-down, up: default-round, checked: default-round-down, font: default-font, fontColor: white, downFontColor: red } }, com.badlogic.gdx.scenes.scene2d.ui.ScrollPane$ScrollPaneStyle: { default: { vScroll: default-scroll, hScrollKnob: default-round-large, background: default-rect, hScroll: default-scroll, vScrollKnob: default-round-large } }, com.badlogic.gdx.scenes.scene2d.ui.SelectBox$SelectBoxStyle: { default: { font: default-font, fontColor: white, background: default-select, scrollStyle: default, listStyle: { font: default-font, selection: default-select-selection } } }, com.badlogic.gdx.scenes.scene2d.ui.SplitPane$SplitPaneStyle: { default-vertical: { handle: default-splitpane-vertical }, default-horizontal: { handle: default-splitpane } }, com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: { default: { titleFont: default-font, background: default-window, titleFontColor: white }, dialog: { titleFont: default-font, background: default-window, titleFontColor: white, stageBackground: dialogDim } }, com.badlogic.gdx.scenes.scene2d.ui.ProgressBar$ProgressBarStyle: { default-horizontal: { background: default-slider, knob: default-slider-knob }, default-vertical: { background: default-slider, knob: default-round-large } }, com.badlogic.gdx.scenes.scene2d.ui.Slider$SliderStyle: { default-horizontal: { background: default-slider, knob: default-slider-knob }, default-vertical: { background: default-slider, knob: default-round-large } }, com.badlogic.gdx.scenes.scene2d.ui.Label$LabelStyle: { default: { font: default-font, fontColor: white } }, com.badlogic.gdx.scenes.scene2d.ui.TextField$TextFieldStyle: { default: { selection: selection, background: textfield, font: default-font, fontColor: white, cursor: cursor } }, com.badlogic.gdx.scenes.scene2d.ui.CheckBox$CheckBoxStyle: { default: { checkboxOn: check-on, checkboxOff: check-off, font: default-font, fontColor: white } }, com.badlogic.gdx.scenes.scene2d.ui.List$ListStyle: { default: { fontColorUnselected: white, selection: selection, fontColorSelected: white, font: default-font } }, com.badlogic.gdx.scenes.scene2d.ui.Touchpad$TouchpadStyle: { default: { background: default-pane, knob: default-round-large } }, com.badlogic.gdx.scenes.scene2d.ui.Tree$TreeStyle: { default: { minus: tree-minus, plus: tree-plus, selection: default-select-selection } }, com.badlogic.gdx.scenes.scene2d.ui.TextTooltip$TextTooltipStyle: { default: { label: { font: default-font, fontColor: white }, background: default-pane, wrapWidth: 150 } }, }