Joise, Kotlin (it's working at least)

Former-commit-id: d5be0e95ba259d566d6d5d20eb576010a149ae7d
Former-commit-id: 9502c7cd7e738147e31d2e9824e48bea24d00abf
This commit is contained in:
Song Minjae
2016-03-14 22:43:28 +09:00
parent 46a553d258
commit 3f49a8aebe
342 changed files with 17386 additions and 360 deletions

View File

@@ -288,7 +288,7 @@ public class GameFontBase implements Font {
}
private int wenQuanYi1IndexY(char c) {
return (c - (c <= 0x4DB5 ? 0x33F3 : 0x33F3 + 0x4A)) / 32;
return (c - (0x33F3 + 0x4A)) / 32;
}
private int wenQuanYi2IndexY(char c) {
@@ -358,24 +358,6 @@ public class GameFontBase implements Font {
public void drawString(float x, float y, String s, Color color) {
// hangul fonts first
hangulSheet.startUse();
// WANSEONG
/*for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (isHangul(ch)) {
int[] hanPos = getHan(ch - 0xAC00);
int glyphW = getWidth("" + ch);
hangulSheet.renderInUse(
Math.round(x
+ getWidthSubstr(s, i + 1) - glyphW
)
, Math.round((H - H_HANGUL) / 2 + y + 1)
, hanPos[0]
, hanPos[1]
);
}
}*/
// JOHAB
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
@@ -456,7 +438,7 @@ public class GameFontBase implements Font {
Math.round(x
+ getWidthSubstr(s, i + 1) - glyphW
)
, Math.round((H - H_UNIHAN) / 2 + y)
, Math.round((H - H_UNIHAN) / 2 + y - 1)
, wenQuanYiIndexX(ch)
, wenQuanYi1IndexY(ch)
);
@@ -475,7 +457,7 @@ public class GameFontBase implements Font {
Math.round(x
+ getWidthSubstr(s, i + 1) - glyphW
)
, Math.round((H - H_UNIHAN) / 2 + y)
, Math.round((H - H_UNIHAN) / 2 + y - 1)
, wenQuanYiIndexX(ch)
, wenQuanYi2IndexY(ch)
);

View File

@@ -1,49 +0,0 @@
package com.Torvald.ImageFont;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
/**
* Created by minjaesong on 16-01-27.
*/
public class GameFontBlack extends GameFontBase {
public GameFontBlack() throws SlickException {
super();
hangulSheet = new SpriteSheet(
"./res/graphics/fonts/han_johab_black.png"
, W_CJK, H_HANGUL
);
asciiSheet = new SpriteSheet(
"./res/graphics/fonts/ascii_majuscule_black.png"
, W_LATIN_WIDE, H
);
asciiSheetEF = new SpriteSheet(
"./res/graphics/fonts/ascii_special_ef_black.png"
, W_LATIN_NARROW, H
);
runicSheet = new SpriteSheet(
"./res/graphics/fonts/futhark_black.png"
, W_LATIN_WIDE, H
);
extASheet = new SpriteSheet(
"./res/graphics/fonts/LatinExtA_majuscule_black.png"
, W_LATIN_WIDE, H
);
extASheetEF = new SpriteSheet(
"./res/graphics/fonts/LatinExtA_ef_black.png"
, W_LATIN_NARROW, H
);
SpriteSheet[] shk = {
asciiSheet
, asciiSheetEF
, hangulSheet
, runicSheet
, extASheet
, extASheetEF
};
sheetKey = shk;
}
}

View File

@@ -2,6 +2,7 @@ package com.Torvald;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.FileWriter;
import java.io.IOException;
@@ -11,7 +12,7 @@ import java.io.IOException;
*/
public class JsonWriter {
public static void writeFile(Object c, String path) throws IOException {
public static void writeToFile(Object c, String path) throws IOException {
JsonElement classElem = new Gson().toJsonTree(c);
String jsonString = classElem.toString();
FileWriter writer = new FileWriter(path);
@@ -19,4 +20,10 @@ public class JsonWriter {
writer.close();
}
public static void writeToFile(JsonObject jsonObject, String path) throws IOException {
FileWriter writer = new FileWriter(path);
writer.write(jsonObject.toString());
writer.close();
}
}

View File

@@ -1,7 +0,0 @@
package com.Torvald.Terrarum.Actors.AI;
/**
* Created by minjaesong on 16-03-02.
*/
public interface ActorAI {
}

View File

@@ -0,0 +1,7 @@
package com.Torvald.Terrarum.Actors.AI
/**
* Created by minjaesong on 16-03-14.
*/
interface ActorAI {
}

View File

@@ -1,12 +0,0 @@
package com.Torvald.Terrarum.Actors;
import com.Torvald.Terrarum.Actors.AI.ActorAI;
/**
* Created by minjaesong on 16-01-31.
*/
public interface AIControlled {
void attachAI(ActorAI ai);
}

View File

@@ -0,0 +1,10 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.Terrarum.Actors.AI.ActorAI
/**
* Created by minjaesong on 16-03-14.
*/
interface AIControlled {
fun attachAI(ai: ActorAI)
}

View File

@@ -0,0 +1,17 @@
package com.Torvald.Terrarum.Actors
import org.newdawn.slick.GameContainer
/**
* Created by minjaesong on 16-03-14.
*/
interface Actor {
fun update(gc: GameContainer, delta_t: Int)
/**
* Valid RefID is equal to or greater than 32768.
* @return Reference ID. (32768-0x7FFF_FFFF_FFFF_FFFF)
*/
var referenceID: Long?
}

View File

@@ -4,14 +4,14 @@ import com.Torvald.Rand.HQRNG;
import com.Torvald.Terrarum.*;
import com.Torvald.Terrarum.GameMap.GameMap;
import com.Torvald.Terrarum.MapDrawer.MapDrawer;
import com.Torvald.Terrarum.NotNull;
import com.Torvald.Terrarum.Nullable;
import com.Torvald.Terrarum.TileProperties.TilePropCodex;
import com.Torvald.spriteAnimation.SpriteAnimation;
import com.jme3.math.FastMath;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import java.io.Serializable;
/**
* Created by minjaesong on 16-01-13.
*/
@@ -245,7 +245,7 @@ public class ActorWithBody implements Actor, Visible, Glowing {
*/
// FIXME abnormal jump behaviour if mass < 2, same thing happens if mass == 0 (but zero mass is invalid anyway).
private void applyGravitation() {
if (!isGrounded()) {
if (!getGrounded()) {
/**
* weight; gravitational force in action
* W = mass * G (9.8 [m/s^2])
@@ -766,11 +766,6 @@ public class ActorWithBody implements Actor, Visible, Glowing {
if (sprite != null) sprite.update(delta_t);
}
@Override
public long getRefID() {
return referenceID;
}
private float clampW(float x) {
if (x < TSIZE + nextHitbox.getWidth() / 2) {
return TSIZE + nextHitbox.getWidth() / 2;
@@ -980,6 +975,17 @@ public class ActorWithBody implements Actor, Visible, Glowing {
this.density = density;
}
@org.jetbrains.annotations.Nullable
@Override
public Long getReferenceID() {
return this.referenceID;
}
@Override
public void setReferenceID(@org.jetbrains.annotations.Nullable Long aLong) {
referenceID = aLong;
}
}
/**

View File

@@ -0,0 +1,781 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.Rand.HQRNG
import com.Torvald.Terrarum.*
import com.Torvald.Terrarum.GameMap.GameMap
import com.Torvald.Terrarum.MapDrawer.MapDrawer
import com.Torvald.Terrarum.TileProperties.TilePropCodex
import com.Torvald.spriteAnimation.SpriteAnimation
import com.jme3.math.FastMath
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
/**
* Created by minjaesong on 16-03-14.
*/
open class ActorWithBody : Actor, Visible, Glowing, Pocketed {
internal var actorValue: ActorValue
override var inventory: ActorInventory? = null
var hitboxTranslateX: Float = 0.toFloat()// relative to spritePosX
var hitboxTranslateY: Float = 0.toFloat()// relative to spritePosY
var baseHitboxW: Int = 0
var baseHitboxH: Int = 0
/**
* Velocity for newtonian sim.
* Fluctuation in, otherwise still, velocity is equal to acceleration.
* Acceleration: used in code like:
* veloY += 3.0
* +3.0 is acceleration. You __accumulate__ acceleration to the velocity.
*/
@Volatile var veloX: Float = 0.toFloat()
@Volatile var veloY: Float = 0.toFloat()
@Transient private val VELO_HARD_LIMIT = 10000f
var grounded = false
@Transient var sprite: SpriteAnimation? = null
@Transient var spriteGlow: SpriteAnimation? = null
/** Default to 'false' */
var isVisible = false
/** Default to 'true' */
var isUpdate = true
var isNoSubjectToGrav = false
var isNoCollideWorld = false
var isNoSubjectToFluidResistance = false
internal var baseSpriteWidth: Int = 0
internal var baseSpriteHeight: Int = 0
override var referenceID: Long? = null
/**
* Positions: top-left point
*/
@Volatile var hitbox: Hitbox? = null
@Volatile @Transient var nextHitbox: Hitbox? = null
/**
* Physical properties
*/
@Volatile @Transient var scale = 1f
@Volatile @Transient var mass = 2f
@Transient private val MASS_LOWEST = 2f
/** Valid range: [0, 1] */
var elasticity = 0f
set(elasticity) {
if (elasticity < 0)
throw IllegalArgumentException("[ActorWithBody] $elasticity: valid elasticity value is [0, 1].")
if (elasticity > 1) {
println("[ActorWithBody] Elasticity were capped to 1.")
this.elasticity = ELASTICITY_MAX
} else
this.elasticity = elasticity * ELASTICITY_MAX
}
@Transient private val ELASTICITY_MAX = 0.993f
private var density = 1000f
/**
* Gravitational Constant G. Load from GameMap.
* [m / s^2]
* s^2 = 1/FPS = 1/60 if FPS is targeted to 60
* meter to pixel : 24/FPS
*/
@Transient private val METER = 24f
/**
* [m / s^2] * SI_TO_GAME_ACC -> [px / IFrame^2]
*/
@Transient private val SI_TO_GAME_ACC = METER / FastMath.sqr(Terrarum.TARGET_FPS.toFloat())
/**
* [m / s] * SI_TO_GAME_VEL -> [px / IFrame]
*/
@Transient private val SI_TO_GAME_VEL = METER / Terrarum.TARGET_FPS
@Transient private var gravitation: Float = 0.toFloat()
@Transient private val DRAG_COEFF = 1f
@Transient private val CONTACT_AREA_TOP = 0
@Transient private val CONTACT_AREA_RIGHT = 1
@Transient private val CONTACT_AREA_BOTTOM = 2
@Transient private val CONTACT_AREA_LEFT = 3
@Transient private val UD_COMPENSATOR_MAX = TSIZE
@Transient private val LR_COMPENSATOR_MAX = TSIZE
@Transient private val TILE_AUTOCLIMB_RATE = 4
/**
* A constant to make falling faster so that the game is more playable
*/
@Transient private val G_MUL_PLAYABLE_CONST = 1.4142f
@Transient private val EVENT_MOVE_TOP = 0
@Transient private val EVENT_MOVE_RIGHT = 1
@Transient private val EVENT_MOVE_BOTTOM = 2
@Transient private val EVENT_MOVE_LEFT = 3
@Transient private val EVENT_MOVE_NONE = -1
@Transient internal var eventMoving = EVENT_MOVE_NONE // cannot collide both X-axis and Y-axis, or else jump control breaks up.
/**
* in milliseconds
*/
@Transient val INVINCIBILITY_TIME = 500
/**
* Will ignore fluid resistance if (submerged height / actor height) <= this var
*/
@Transient private val FLUID_RESISTANCE_IGNORE_THRESHOLD_RATIO = 0.2f
@Transient private val FLUID_RESISTANCE_APPLY_FULL_RATIO = 0.5f
@Transient private val map: GameMap
init {
referenceID = HQRNG().nextLong()
actorValue = ActorValue()
map = Terrarum.game.map
}
/**
* @param w
* *
* @param h
* *
* @param tx +: translate drawn sprite to LEFT.
* *
* @param ty +: translate drawn sprite to DOWN.
* *
* @see ActorWithBody.drawBody
* @see ActorWithBody.drawGlow
*/
fun setHitboxDimension(w: Int, h: Int, tx: Int, ty: Int) {
baseHitboxH = h
baseHitboxW = w
hitboxTranslateX = tx.toFloat()
hitboxTranslateY = ty.toFloat()
}
/**
* Set hitbox position from bottom-center point
* @param x
* *
* @param y
*/
fun setPosition(x: Float, y: Float) {
hitbox = Hitbox(
x - (baseHitboxW / 2 - hitboxTranslateX) * scale, y - (baseHitboxH - hitboxTranslateY) * scale, baseHitboxW * scale, baseHitboxH * scale)
nextHitbox = Hitbox(
x - (baseHitboxW / 2 - hitboxTranslateX) * scale, y - (baseHitboxH - hitboxTranslateY) * scale, baseHitboxW * scale, baseHitboxH * scale)
}
override fun update(gc: GameContainer, delta_t: Int) {
if (isUpdate) {
/**
* Update variables
*/
if (this is Player) {
isNoSubjectToGrav = isPlayerNoClip
isNoCollideWorld = isPlayerNoClip
isNoSubjectToFluidResistance = isPlayerNoClip
}
if (mass < MASS_LOWEST) mass = MASS_LOWEST // clamp to minimum possible mass
if (sprite != null) {
baseSpriteHeight = sprite!!.height
baseSpriteWidth = sprite!!.width
}
gravitation = map.gravitation
AUTO_CLIMB_RATE = Math.min(TSIZE / 8 * FastMath.sqrt(scale), TSIZE.toFloat()).toInt()
if (!isNoSubjectToGrav) {
applyGravitation()
applyBuoyancy()
}
// hard limit velocity
if (veloX > VELO_HARD_LIMIT) veloX = VELO_HARD_LIMIT
if (veloY > VELO_HARD_LIMIT) veloY = VELO_HARD_LIMIT
// limit velocity by fluid resistance
//int tilePropResistance = getTileMvmtRstc();
//if (!noSubjectToFluidResistance) {
// veloX *= mvmtRstcToMultiplier(tilePropResistance);
// veloY *= mvmtRstcToMultiplier(tilePropResistance);
//}
// Set 'next' positions to fiddle with
updateNextHitboxFromVelo()
// if not horizontally moving then ...
//if (Math.abs(veloX) < 0.5) { // fix for special situations (see fig. 1 at the bottom of the source)
// updateVerticalPos();
// updateHorizontalPos();
//}
//else {
updateHorizontalPos()
updateVerticalPos()
//}
updateHitboxX()
updateHitboxY()
clampNextHitbox()
clampHitbox()
}
}
/**
* Apply gravitation to the every falling body (unless not levitating)
* Apply only if not grounded; normal force is not implemented (and redundant)
* so we manually reset G to zero (not applying G. force) if grounded.
*/
// FIXME abnormal jump behaviour if mass < 2, same thing happens if mass == 0 (but zero mass is invalid anyway).
private fun applyGravitation() {
if (!grounded) {
/**
* weight; gravitational force in action
* W = mass * G (9.8 [m/s^2])
*/
val W = gravitation * mass
/**
* Drag of atmosphere
* D = Cd (drag coefficient) * 0.5 * rho (density) * V^2 (velocity) * A (area)
*/
val A = scale * scale
val D = DRAG_COEFF * 0.5f * 1.292f * veloY * veloY * A
val fluidResistance = tileMvmtRstc
veloY += clampCeil(
(W - D) / mass * SI_TO_GAME_ACC * G_MUL_PLAYABLE_CONST, VELO_HARD_LIMIT)// * mvmtRstcToMultiplier(fluidResistance) // eliminate shoot-up from fluids
}
}
private fun updateVerticalPos() {
if (!isNoCollideWorld) {
// check downward
if (veloY >= 0) {
// order of the if-elseif chain is IMPORTANT
if (isColliding(CONTACT_AREA_BOTTOM)) {
adjustHitBottom()
elasticReflectY()
grounded = true
} else if (isColliding(CONTACT_AREA_BOTTOM, 0, 1)) {
elasticReflectY()
grounded = true
} else {
grounded = false
}
} else if (veloY < 0) {
grounded = false
// order of the if-elseif chain is IMPORTANT
if (isColliding(CONTACT_AREA_TOP)) {
adjustHitTop()
elasticReflectY()
} else if (isColliding(CONTACT_AREA_TOP, 0, -1)) {
elasticReflectY() // for reversed gravity
} else {
}
}
}
}
private fun adjustHitBottom() {
val newX = nextHitbox!!.pointedX // look carefully, getPos or getPointed
// int-ify posY of nextHitbox
nextHitbox!!.setPositionYFromPoint(FastMath.floor(nextHitbox!!.pointedY).toFloat())
var newYOff = 0 // always positive
var colliding: Boolean
do {
newYOff += 1
colliding = isColliding(CONTACT_AREA_BOTTOM, 0, -newYOff)
} while (colliding)
val newY = nextHitbox!!.pointedY - newYOff
nextHitbox!!.setPositionFromPoint(newX, newY)
}
private fun adjustHitTop() {
val newX = nextHitbox!!.posX
// int-ify posY of nextHitbox
nextHitbox!!.setPositionY(FastMath.ceil(nextHitbox!!.posY).toFloat())
var newYOff = 0 // always positive
var colliding: Boolean
do {
newYOff += 1
colliding = isColliding(CONTACT_AREA_TOP, 0, newYOff)
} while (colliding)
val newY = nextHitbox!!.posY + newYOff
nextHitbox!!.setPosition(newX, newY)
}
private fun updateHorizontalPos() {
if (!isNoCollideWorld) {
// check right
if (veloX >= 0.5) {
// order of the if-elseif chain is IMPORTANT
if (isColliding(CONTACT_AREA_RIGHT) && !isColliding(CONTACT_AREA_LEFT)) {
adjustHitRight()
elasticReflectX()
} else if (isColliding(CONTACT_AREA_RIGHT, 1, 0) && !isColliding(CONTACT_AREA_LEFT, -1, 0)) {
elasticReflectX()
} else {
}
} else if (veloX <= -0.5) {
// System.out.println("collidingleft");
// order of the if-elseif chain is IMPORTANT
if (isColliding(CONTACT_AREA_LEFT) && !isColliding(CONTACT_AREA_RIGHT)) {
adjustHitLeft()
elasticReflectX()
} else if (isColliding(CONTACT_AREA_LEFT, -1, 0) && !isColliding(CONTACT_AREA_RIGHT, 1, 0)) {
elasticReflectX()
} else {
}
} else {
// System.out.println("updatehorizontal - |velo| < 0.5");
if (isColliding(CONTACT_AREA_LEFT) || isColliding(CONTACT_AREA_RIGHT)) {
elasticReflectX()
}
}
}
}
private fun adjustHitRight() {
val newY = nextHitbox!!.posY // look carefully, getPos or getPointed
// int-ify posY of nextHitbox
nextHitbox!!.setPositionX(FastMath.floor(nextHitbox!!.posX + nextHitbox!!.width) - nextHitbox!!.width)
var newXOff = 0 // always positive
var colliding: Boolean
do {
newXOff += 1
colliding = isColliding(CONTACT_AREA_BOTTOM, -newXOff, 0)
} while (newXOff < TSIZE && colliding)
val newX = nextHitbox!!.posX - newXOff
nextHitbox!!.setPosition(newX, newY)
}
private fun adjustHitLeft() {
val newY = nextHitbox!!.posY
// int-ify posY of nextHitbox
nextHitbox!!.setPositionX(FastMath.ceil(nextHitbox!!.posX).toFloat())
var newXOff = 0 // always positive
var colliding: Boolean
do {
newXOff += 1
colliding = isColliding(CONTACT_AREA_TOP, newXOff, 0)
} while (newXOff < TSIZE && colliding)
val newX = nextHitbox!!.posX + newXOff
nextHitbox!!.setPosition(newX, newY) // + 1; float-point rounding compensation (i think...)
}
private fun elasticReflectX() {
if (veloX != 0f) veloX = -veloX * elasticity
}
private fun elasticReflectY() {
if (veloY != 0f) veloY = -veloY * elasticity
}
private fun isColliding(side: Int, tx: Int = 0, ty: Int = 0): Boolean {
return getContactingArea(side, tx, ty) > 1
}
private fun getContactingArea(side: Int, translateX: Int = 0, translateY: Int = 0): Int {
var contactAreaCounter = 0
for (i in 0..Math.round(if (side % 2 == 0) nextHitbox!!.width else nextHitbox!!.height) - 1) {
// set tile positions
val tileX: Int
val tileY: Int
/*if (side == CONTACT_AREA_BOTTOM) {
tileX = div16TruncateToMapWidth(Math.round(nextHitbox.getHitboxStart().getX())
+ i + translateX);
tileY = div16TruncateToMapHeight(FastMath.floor(nextHitbox.getHitboxEnd().getY())
+ translateY);
}
else if (side == CONTACT_AREA_TOP) {
tileX = div16TruncateToMapWidth(Math.round(nextHitbox.getHitboxStart().getX())
+ i + translateX);
tileY = div16TruncateToMapHeight(FastMath.ceil(nextHitbox.getHitboxStart().getY())
+ translateY);
}
else if (side == CONTACT_AREA_RIGHT) {
tileX = div16TruncateToMapWidth(FastMath.floor(nextHitbox.getHitboxEnd().getX())
+ translateX);
tileY = div16TruncateToMapHeight(Math.round(nextHitbox.getHitboxStart().getY())
+ i + translateY);
}
else if (side == CONTACT_AREA_LEFT) {
tileX = div16TruncateToMapWidth(FastMath.ceil(nextHitbox.getHitboxStart().getX())
+ translateX);
tileY = div16TruncateToMapHeight(Math.round(nextHitbox.getHitboxStart().getY())
+ i + translateY);
}*/
if (side == CONTACT_AREA_BOTTOM) {
tileX = div16TruncateToMapWidth(Math.round(nextHitbox!!.hitboxStart.x)
+ i + translateX)
tileY = div16TruncateToMapHeight(Math.round(nextHitbox!!.hitboxEnd.y) + translateY)
} else if (side == CONTACT_AREA_TOP) {
tileX = div16TruncateToMapWidth(Math.round(nextHitbox!!.hitboxStart.x)
+ i + translateX)
tileY = div16TruncateToMapHeight(Math.round(nextHitbox!!.hitboxStart.y) + translateY)
} else if (side == CONTACT_AREA_RIGHT) {
tileX = div16TruncateToMapWidth(Math.round(nextHitbox!!.hitboxEnd.x) + translateX)
tileY = div16TruncateToMapHeight(Math.round(nextHitbox!!.hitboxStart.y)
+ i + translateY)
} else if (side == CONTACT_AREA_LEFT) {
tileX = div16TruncateToMapWidth(Math.round(nextHitbox!!.hitboxStart.x) + translateX)
tileY = div16TruncateToMapHeight(Math.round(nextHitbox!!.hitboxStart.y)
+ i + translateY)
} else {
throw IllegalArgumentException(side.toString() + ": Wrong side input")
}
// evaluate
if (TilePropCodex.getProp(map.getTileFromTerrain(tileX, tileY)).isSolid) {
contactAreaCounter += 1
}
}
return contactAreaCounter
}
/**
* [N] = [kg * m / s^2]
* F(bo) = density * submerged_volume * gravitational_acceleration [N]
*/
private fun applyBuoyancy() {
val fluidDensity = tileDensity
val submergedVolume = submergedVolume
if (!isPlayerNoClip && !grounded) {
// System.out.println("density: "+density);
veloY -= ((fluidDensity - this.density).toDouble()
* map.gravitation.toDouble() * submergedVolume.toDouble()
* Math.pow(mass.toDouble(), -1.0)
* SI_TO_GAME_ACC.toDouble()).toFloat()
}
}
private //System.out.println("fluidHeight: "+fluidHeight+", submerged: "+submergedVolume);
//submergedHeight / TILE_SIZE * 1^2 (pixel to meter)
val submergedVolume: Float
get() {
val GAME_TO_SI_VOL = FastMath.pow(1f / METER, 3f)
if (density > 0) {
return submergedHeight *
nextHitbox!!.width * nextHitbox!!.width *
GAME_TO_SI_VOL
} else {
return 0f
}
}
private val submergedHeight: Float
get() = FastMath.clamp(
nextHitbox!!.pointedY - fluidLevel, 0f, nextHitbox!!.height)
private val fluidLevel: Int
get() {
val tilePosXStart = Math.round(nextHitbox!!.posX / TSIZE)
val tilePosXEnd = Math.round(nextHitbox!!.hitboxEnd.x / TSIZE)
val tilePosY = Math.round(nextHitbox!!.posY / TSIZE)
var fluidHeight = 2147483647
for (x in tilePosXStart..tilePosXEnd) {
val tile = map.getTileFromTerrain(x, tilePosY)
if (TilePropCodex.getProp(tile).isFluid && tilePosY * TSIZE < fluidHeight) {
fluidHeight = tilePosY * TSIZE
}
}
return fluidHeight
}
/**
* Get highest friction value from feet tiles.
* @return
*/
private //get density
val tileFriction: Int
get() {
var friction = 0
val tilePosXStart = Math.round(nextHitbox!!.posX / TSIZE)
val tilePosXEnd = Math.round(nextHitbox!!.hitboxEnd.x / TSIZE)
val tilePosY = Math.round(nextHitbox!!.pointedY / TSIZE)
for (x in tilePosXStart..tilePosXEnd) {
val tile = map.getTileFromTerrain(x, tilePosY)
if (TilePropCodex.getProp(tile).isFluid) {
val thisFluidDensity = TilePropCodex.getProp(tile).friction
if (thisFluidDensity > friction) friction = thisFluidDensity
}
}
return friction
}
/**
* Get highest movement resistance value from tiles that the body occupies.
* @return
*/
private //get density
val tileMvmtRstc: Int
get() {
var resistance = 0
val tilePosXStart = Math.round(nextHitbox!!.posX / TSIZE)
val tilePosYStart = Math.round(nextHitbox!!.posY / TSIZE)
val tilePosXEnd = Math.round(nextHitbox!!.hitboxEnd.x / TSIZE)
val tilePosYEnd = Math.round(nextHitbox!!.hitboxEnd.y / TSIZE)
for (y in tilePosYStart..tilePosYEnd) {
for (x in tilePosXStart..tilePosXEnd) {
val tile = map.getTileFromTerrain(x, y)
if (TilePropCodex.getProp(tile).isFluid) {
val thisFluidDensity = TilePropCodex.getProp(tile).movementResistance
if (thisFluidDensity > resistance) resistance = thisFluidDensity
}
}
}
return resistance
}
/**
* Get highest density (specific gravity) value from tiles that the body occupies.
* @return
*/
private //get density
val tileDensity: Int
get() {
var density = 0
val tilePosXStart = Math.round(nextHitbox!!.posX / TSIZE)
val tilePosYStart = Math.round(nextHitbox!!.posY / TSIZE)
val tilePosXEnd = Math.round(nextHitbox!!.hitboxEnd.x / TSIZE)
val tilePosYEnd = Math.round(nextHitbox!!.hitboxEnd.y / TSIZE)
for (y in tilePosYStart..tilePosYEnd) {
for (x in tilePosXStart..tilePosXEnd) {
val tile = map.getTileFromTerrain(x, y)
if (TilePropCodex.getProp(tile).isFluid) {
val thisFluidDensity = TilePropCodex.getProp(tile).density
if (thisFluidDensity > density) density = thisFluidDensity
}
}
}
return density
}
private fun mvmtRstcToMultiplier(movementResistanceValue: Int): Float {
return 1f / (1 + movementResistanceValue / 16f)
}
private fun clampHitbox() {
hitbox!!.setPositionFromPoint(
clampW(hitbox!!.pointedX), clampH(hitbox!!.pointedY))
}
private fun clampNextHitbox() {
nextHitbox!!.setPositionFromPoint(
clampW(nextHitbox!!.pointedX), clampH(nextHitbox!!.pointedY))
}
private fun updateNextHitboxFromVelo() {
val fluidResistance = mvmtRstcToMultiplier(tileMvmtRstc)
val submergedRatio = FastMath.clamp(
submergedHeight / nextHitbox!!.height, 0f, 1f)
val applyResistance = !isNoSubjectToFluidResistance && submergedRatio > FLUID_RESISTANCE_IGNORE_THRESHOLD_RATIO
val resistanceMulInterValueSize = FLUID_RESISTANCE_APPLY_FULL_RATIO - FLUID_RESISTANCE_IGNORE_THRESHOLD_RATIO
val resistanceMultiplier = FastMath.interpolateLinear(
(submergedRatio - FLUID_RESISTANCE_IGNORE_THRESHOLD_RATIO) * FastMath.pow(resistanceMulInterValueSize, -1f), 0f, 1f)
val adjustedResistance = FastMath.interpolateLinear(
resistanceMultiplier, 1f, fluidResistance)
nextHitbox!!.set(
Math.round(hitbox!!.posX + veloX * (if (!applyResistance) 1f else adjustedResistance)).toFloat()
, Math.round(hitbox!!.posY + veloY * (if (!applyResistance) 1f else adjustedResistance)).toFloat()
, Math.round(baseHitboxW * scale).toFloat()
, Math.round(baseHitboxH * scale).toFloat())
/** Full quantisation; wonder what havoc these statements would wreak...
*/
}
private fun updateHitboxX() {
hitbox!!.setDimension(
nextHitbox!!.width, nextHitbox!!.height)
hitbox!!.setPositionX(nextHitbox!!.posX)
}
private fun updateHitboxY() {
hitbox!!.setDimension(
nextHitbox!!.width, nextHitbox!!.height)
hitbox!!.setPositionY(nextHitbox!!.posY)
}
override fun drawGlow(gc: GameContainer, g: Graphics) {
if (isVisible && spriteGlow != null) {
if (!sprite!!.flippedHorizontal()) {
spriteGlow!!.render(g, hitbox!!.posX - hitboxTranslateX * scale, hitbox!!.posY + hitboxTranslateY * scale - (baseSpriteHeight - baseHitboxH) * scale + 2, scale)
} else {
spriteGlow!!.render(g, hitbox!!.posX - scale, hitbox!!.posY + hitboxTranslateY * scale - (baseSpriteHeight - baseHitboxH) * scale + 2, scale)
}
}
}
override fun drawBody(gc: GameContainer, g: Graphics) {
if (isVisible && sprite != null) {
if (!sprite!!.flippedHorizontal()) {
sprite!!.render(g, hitbox!!.posX - hitboxTranslateX * scale, hitbox!!.posY + hitboxTranslateY * scale - (baseSpriteHeight - baseHitboxH) * scale + 2, scale)
} else {
sprite!!.render(g, hitbox!!.posX - scale, hitbox!!.posY + hitboxTranslateY * scale - (baseSpriteHeight - baseHitboxH) * scale + 2, scale)
}
}
}
override fun updateGlowSprite(gc: GameContainer, delta_t: Int) {
if (spriteGlow != null) spriteGlow!!.update(delta_t)
}
override fun updateBodySprite(gc: GameContainer, delta_t: Int) {
if (sprite != null) sprite!!.update(delta_t)
}
private fun clampW(x: Float): Float {
if (x < TSIZE + nextHitbox!!.width / 2) {
return TSIZE + nextHitbox!!.width / 2
} else if (x >= (map.width * TSIZE).toFloat() - TSIZE.toFloat() - nextHitbox!!.width / 2) {
return (map.width * TSIZE).toFloat() - 1f - TSIZE.toFloat() - nextHitbox!!.width / 2
} else {
return x
}
}
private fun clampH(y: Float): Float {
if (y < TSIZE + nextHitbox!!.height) {
return TSIZE + nextHitbox!!.height
} else if (y >= (map.height * TSIZE).toFloat() - TSIZE.toFloat() - nextHitbox!!.height) {
return (map.height * TSIZE).toFloat() - 1f - TSIZE.toFloat() - nextHitbox!!.height
} else {
return y
}
}
private fun clampWtile(x: Int): Int {
if (x < 0) {
return 0
} else if (x >= map.width) {
return map.width - 1
} else {
return x
}
}
private fun clampHtile(x: Int): Int {
if (x < 0) {
return 0
} else if (x >= map.height) {
return map.height - 1
} else {
return x
}
}
private val isPlayerNoClip: Boolean
get() = this is Player && this.isNoClip()
private fun quantiseTSize(v: Float): Int {
return FastMath.floor(v / TSIZE) * TSIZE
}
fun setDensity(density: Int) {
if (density < 0)
throw IllegalArgumentException("[ActorWithBody] $density: density cannot be negative.")
this.density = density.toFloat()
}
companion object {
@Transient private val TSIZE = MapDrawer.TILE_SIZE
private var AUTO_CLIMB_RATE = TSIZE / 8
private fun div16(x: Int): Int {
if (x < 0) {
throw IllegalArgumentException("div16: Positive integer only: " + x.toString())
}
return x and 0x7FFFFFFF shr 4
}
private fun div16TruncateToMapWidth(x: Int): Int {
if (x < 0)
return 0
else if (x >= Terrarum.game.map.width shl 4)
return Terrarum.game.map.width - 1
else
return x and 0x7FFFFFFF shr 4
}
private fun div16TruncateToMapHeight(y: Int): Int {
if (y < 0)
return 0
else if (y >= Terrarum.game.map.height shl 4)
return Terrarum.game.map.height - 1
else
return y and 0x7FFFFFFF shr 4
}
private fun mod16(x: Int): Int {
if (x < 0) {
throw IllegalArgumentException("mod16: Positive integer only: " + x.toString())
}
return x and 15
}
private fun clampCeil(x: Float, ceil: Float): Float {
return if (Math.abs(x) > ceil) ceil else x
}
}
}
/**
* Give new random ReferenceID and initialise ActorValue
*/
/**
= = ↑
=== ===@!
=↑ =↑
=↑ =
=↑ =
=@ (pressing R) =
================== ==================
Fig. 1: the fix was not applied
*/

View File

@@ -0,0 +1,20 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.Terrarum.GameItem.InventoryItem
/**
* Created by minjaesong on 16-03-14.
*/
interface CanBeStoredAsItem {
fun attachItemData()
fun getItemWeight(): Float
fun stopUpdateAndDraw()
fun resumeUpdateAndDraw()
var itemData: InventoryItem?
}

View File

@@ -0,0 +1,14 @@
package com.Torvald.Terrarum.Actors
import org.newdawn.slick.Input
/**
* Created by minjaesong on 16-03-14.
*/
interface Controllable {
fun processInput(input: Input)
fun keyPressed(key: Int, c: Char)
}

View File

@@ -12,7 +12,7 @@ import java.io.IOException;
/**
* Created by minjaesong on 16-02-05.
*/
public class CreatureBuildFactory {
public class CreatureFactory {
private static final String JSONPATH = "./res/raw/";
@@ -62,7 +62,6 @@ public class CreatureBuildFactory {
actor.inventory = new ActorInventory((int) actor.actorValue.get("encumberance"), true);
return actor;
}

View File

@@ -0,0 +1,127 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.JsonFetcher
import com.Torvald.Rand.Fudge3
import com.Torvald.Rand.HQRNG
import com.Torvald.Terrarum.LangPack.Lang
import com.google.gson.JsonObject
import org.newdawn.slick.SlickException
import java.io.IOException
/**
* Created by minjaesong on 16-03-14.
*/
private const val JSONPATH = "./res/raw/"
class CreatureFactory {
@Throws(IOException::class, SlickException::class)
fun build(jsonFileName: String): ActorWithBody {
val jsonObj = JsonFetcher.readJson(JSONPATH + jsonFileName)
val actor = ActorWithBody()
val elementsString = arrayOf("racename", "racenameplural")
val elementsFloat = arrayOf("baseheight", "basemass", "accel", "toolsize", "encumbrance")
val elementsFloatVariable = arrayOf("strength", "speed", "jumppower", "scale", "speed")
val elementsBoolean = arrayOf("intelligent")
val elementsMultiplyFromOne = arrayOf("physiquemult")
setAVStrings(actor, elementsString, jsonObj)
setAVFloats(actor, elementsFloat, jsonObj)
setAVFloatsVariable(actor, elementsFloatVariable, jsonObj)
setAVMultiplyFromOne(actor, elementsMultiplyFromOne, jsonObj)
setAVBooleans(actor, elementsBoolean, jsonObj)
actor.actorValue.set("accel", Player.WALK_ACCEL_BASE)
actor.actorValue.set("accelmult", 1f)
actor.inventory = (ActorInventory(actor.actorValue.get("encumbrance") as Int, true))
return actor
}
/**
* Fetch and set actor values that have 'variable' appended. E.g. strength
* @param p
* *
* @param elemSet
* *
* @param jsonObject
*/
private fun setAVFloatsVariable(p: ActorWithBody, elemSet: Array<String>, jsonObject: JsonObject) {
for (s in elemSet) {
val baseValue = jsonObject.get(s).asFloat
// roll fudge dice and get value [-3, 3] as [0, 6]
val varSelected = Fudge3(HQRNG()).rollForArray()
// get multiplier from json. Assuming percentile
val multiplier = jsonObject.get(s + "variable").asJsonArray.get(varSelected).asInt
val realValue = baseValue * multiplier / 100f
p.actorValue.set(s, realValue)
}
}
/**
* Fetch and set string actor values
* @param p
* *
* @param elemSet
* *
* @param jsonObject
*/
private fun setAVStrings(p: ActorWithBody, elemSet: Array<String>, jsonObject: JsonObject) {
for (s in elemSet) {
val key = jsonObject.get(s).asString
p.actorValue.set(s, Lang.get(key))
}
}
/**
* Fetch and set float actor values
* @param p
* *
* @param elemSet
* *
* @param jsonObject
*/
private fun setAVFloats(p: ActorWithBody, elemSet: Array<String>, jsonObject: JsonObject) {
for (s in elemSet) {
p.actorValue.set(s, jsonObject.get(s).asFloat)
}
}
/**
* Fetch and set actor values that should multiplier be applied to the base value of 1.
* E.g. physiquemult
* @param p
* *
* @param elemSet
* *
* @param jsonObject
*/
private fun setAVMultiplyFromOne(p: ActorWithBody, elemSet: Array<String>, jsonObject: JsonObject) {
for (s in elemSet) {
val baseValue = 1f
// roll fudge dice and get value [-3, 3] as [0, 6]
val varSelected = Fudge3(HQRNG()).rollForArray()
// get multiplier from json. Assuming percentile
val multiplier = jsonObject.get(s).asJsonArray.get(varSelected).asInt
val realValue = baseValue * multiplier / 100f
p.actorValue.set(s, realValue)
}
}
private fun setAVBooleans(p: ActorWithBody, elemSet: Array<String>, jsonObject: JsonObject) {
for (s in elemSet) {
p.actorValue.set(s, jsonObject.get(s).asBoolean)
}
}
}

View File

@@ -0,0 +1,15 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.Terrarum.Actors.Faction.Faction
import java.util.*
/**
* Created by minjaesong on 16-03-14.
*/
interface Factionable {
fun assignFaction(f: Faction)
fun unassignFaction(f: Faction)
var faction: HashSet<Faction>?
}

View File

@@ -0,0 +1,13 @@
package com.Torvald.Terrarum.Actors
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
/**
* Created by minjaesong on 16-03-14.
*/
interface Glowing {
fun drawGlow(gc: GameContainer, g: Graphics)
fun updateGlowSprite(gc: GameContainer, delta: Int)
}

View File

@@ -0,0 +1,19 @@
package com.Torvald.Terrarum.Actors
import java.util.*
/**
* Created by minjaesong on 16-03-14.
*/
interface LandHolder {
/**
* Absolute tile index. index(x, y) = y * map.width + x
* The arraylist will be saved in JSON format with GSON.
*/
var houseDesignation: ArrayList<Int>?
fun addHouseTile(x: Int, y: Int);
fun removeHouseTile(x: Int, y: Int);
fun clearHouseDesignation();
}

View File

@@ -0,0 +1,24 @@
package com.Torvald.Terrarum.Actors
/**
* Created by minjaesong on 16-03-14.
*/
interface Luminous {
/**
* Recommended implementation:
*
override var luminosity: Char
get() = if (actorValue.get("luminosity") != null) {
actorValue.get("luminosity") as Char
}
else {
0 as Char
}
set(value) {
actorValue.set("luminosity", value)
}
*/
var luminosity: Char
}

View File

@@ -0,0 +1,103 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.Terrarum.Actors.AI.ActorAI
import com.Torvald.Terrarum.Actors.Faction.Faction
import com.Torvald.Terrarum.GameItem.InventoryItem
import com.Torvald.Terrarum.Terrarum
import org.newdawn.slick.GameContainer
import java.util.*
/**
* Created by minjaesong on 16-03-14.
*/
open class NPCIntelligentBase : ActorWithBody()
, AIControlled, Pocketed, CanBeStoredAsItem, Factionable, LandHolder {
override var itemData: InventoryItem? = null
@Transient private var ai: ActorAI? = null
override var inventory: ActorInventory? = null
private val factionSet = HashSet<Faction>()
override var referenceID: Long? = null
override var faction: HashSet<Faction>? = null
override var houseDesignation: ArrayList<Int>? = null
/**
* Absolute tile index. index(x, y) = y * map.width + x
* The arraylist will be saved in JSON format with GSON.
*/
private var houseTiles = ArrayList<Int>()
override fun assignFaction(f: Faction) {
factionSet.add(f)
}
override fun unassignFaction(f: Faction) {
factionSet.remove(f)
}
override fun attachItemData() {
itemData = object : InventoryItem {
override fun getItemID(): Long {
return 0
}
override fun getWeight(): Float {
return 0f
}
override fun effectWhileInPocket(gc: GameContainer, delta_t: Int) {
}
override fun effectWhenPickedUp(gc: GameContainer, delta_t: Int) {
}
override fun primaryUse(gc: GameContainer, delta_t: Int) {
}
override fun secondaryUse(gc: GameContainer, delta_t: Int) {
}
override fun effectWhenThrownAway(gc: GameContainer, delta_t: Int) {
}
}
}
override fun getItemWeight(): Float {
return mass
}
override fun addHouseTile(x: Int, y: Int) {
houseTiles.add(Terrarum.game.map.width * y + x)
}
override fun removeHouseTile(x: Int, y: Int) {
houseTiles.remove(Terrarum.game.map.width * y + x)
}
override fun clearHouseDesignation() {
houseTiles.clear()
}
override fun stopUpdateAndDraw() {
isUpdate = false
isVisible = false
}
override fun resumeUpdateAndDraw() {
isUpdate = true
isVisible = true
}
override fun attachAI(ai: ActorAI) {
this.ai = ai
}
}

View File

@@ -13,7 +13,7 @@ import java.io.IOException;
/**
* Created by minjaesong on 16-02-03.
*/
public class PBFSigrid {
public class PFSigrid {
private static String FACTION_PATH = "./res/raw/";
@@ -36,7 +36,6 @@ public class PBFSigrid {
p.spriteGlow.setAsVisible();
p.spriteGlow.composeSprite();
p.actorValue = new ActorValue();
p.actorValue.set("scale", 1.0f);
p.actorValue.set("speed", 4.0f);
@@ -66,7 +65,7 @@ public class PBFSigrid {
p.setHitboxDimension(18, 46, 8, 0);
p.inventory = new ActorInventory(0x7FFFFFFF, true);
p.setInventory(new ActorInventory(0x7FFFFFFF, true));
p.setPosition(4096 * 16, 300 * 16);

View File

@@ -0,0 +1,96 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.JsonFetcher
import com.Torvald.Terrarum.Actors.Faction.Faction
import com.Torvald.spriteAnimation.SpriteAnimation
import com.google.gson.JsonObject
import org.newdawn.slick.SlickException
import java.io.IOException
/**
* Created by minjaesong on 16-03-14.
*/
class PFSigrid {
@Throws(SlickException::class)
fun build(): Player {
val p = Player()
p.sprite = SpriteAnimation()
p.sprite!!.setDimension(28, 51)
p.sprite!!.setSpriteImage("res/graphics/sprites/test_player.png")
p.sprite!!.setDelay(200)
p.sprite!!.setRowsAndFrames(1, 1)
p.sprite!!.setAsVisible()
p.sprite!!.composeSprite()
p.spriteGlow = SpriteAnimation()
p.spriteGlow!!.setDimension(28, 51)
p.spriteGlow!!.setSpriteImage("res/graphics/sprites/test_player_glow.png")
p.spriteGlow!!.setDelay(200)
p.spriteGlow!!.setRowsAndFrames(1, 1)
p.spriteGlow!!.setAsVisible()
p.spriteGlow!!.composeSprite()
p.actorValue = ActorValue()
p.actorValue.set("scale", 1.0f)
p.actorValue.set("speed", 4.0f)
p.actorValue.set("speedmult", 1.0f)
p.actorValue.set("accel", Player.WALK_ACCEL_BASE)
p.actorValue.set("accelmult", 1.0f)
p.actorValue.set("jumppower", 5f)
p.actorValue.set("basemass", 80f)
p.actorValue.set("physiquemult", 1) // Constant 1.0 for player, meant to be used by random mobs
/**
* fixed value, or 'base value', from creature strength of Dwarf Fortress.
* Human race uses 1000. (see CreatureHuman.json)
*/
p.actorValue.set("strength", 1414)
p.actorValue.set("encumbrance", 1000)
p.actorValue.set("name", "Sigrid")
p.actorValue.set("intelligent", true)
p.actorValue.set("luminosity", 22819)
p.actorValue.set("selectedtile", 16)
p.setHitboxDimension(18, 46, 8, 0)
p.inventory = ActorInventory(0x7FFFFFFF, true)
p.setPosition((4096 * 16).toFloat(), (300 * 16).toFloat())
p.assignFaction(loadFactioningData("FactionSigrid.json"))
return p
}
private fun loadFactioningData(filename: String): Faction {
var jsonObject: JsonObject? = null
try {
jsonObject = JsonFetcher.readJson(FACTION_PATH + filename)
} catch (e: IOException) {
e.printStackTrace()
System.exit(-1)
}
val faction = Faction(jsonObject!!.get("factionname").asString)
jsonObject.get("factionamicable").asJsonArray.forEach { jobj -> faction.addFactionAmicable(jobj.asString) }
jsonObject.get("factionneutral").asJsonArray.forEach { jobj -> faction.addFactionNeutral(jobj.asString) }
jsonObject.get("factionhostile").asJsonArray.forEach { jobj -> faction.addFactionHostile(jobj.asString) }
jsonObject.get("factionfearful").asJsonArray.forEach { jobj -> faction.addFactionFearful(jobj.asString) }
return faction
}
companion object {
private val FACTION_PATH = "./res/raw/"
}
}

View File

@@ -0,0 +1,25 @@
package com.Torvald.Terrarum.Actors
import org.newdawn.slick.Color
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
/**
* Created by minjaesong on 16-03-14.
*/
class PhysTestBall : ActorWithBody {
constructor(): super() {
setHitboxDimension(16, 16, 0, 0)
isVisible = true
mass = 10f
}
override fun drawBody(gc: GameContainer, g: Graphics) {
g.color = Color.orange
g.fillOval(
hitbox!!.getPosX(),
hitbox!!.getPosY(),
hitbox!!.getWidth(),
hitbox!!.getHeight())
}
}

View File

@@ -522,16 +522,6 @@ public class Player extends ActorWithBody implements Controllable, Pocketed, Fac
}
}
@Override
public ActorInventory getInventory() {
return inventory;
}
@Override
public void overwriteInventory(ActorInventory inventory) {
this.inventory = inventory;
}
public boolean isNoClip() {
return noClip;
}

View File

@@ -0,0 +1,524 @@
package com.Torvald.Terrarum.Actors
import com.Torvald.Terrarum.Actors.Faction.Faction
import com.Torvald.Terrarum.GameControl.EnumKeyFunc
import com.Torvald.Terrarum.GameControl.KeyMap
import com.Torvald.Terrarum.MapDrawer.MapDrawer
import com.Torvald.Terrarum.Terrarum
import com.Torvald.spriteAnimation.SpriteAnimation
import com.jme3.math.FastMath
import org.lwjgl.input.Controller
import org.lwjgl.input.Controllers
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Input
import org.newdawn.slick.SlickException
import java.util.*
/**
* Created by minjaesong on 16-03-14.
*/
/**
* empirical value.
*/
// private transient final float JUMP_ACCELERATION_MOD = ???f / 10000f; //quadratic mode
@Transient private const val JUMP_ACCELERATION_MOD = 170f / 10000f //linear mode
@Transient private const val WALK_FRAMES_TO_MAX_ACCEL = 6
@Transient private const val LEFT = 1
@Transient private const val RIGHT = 2
@Transient private const val KEY_NULL = -1
class Player : ActorWithBody, Controllable, Pocketed, Factionable, Luminous, LandHolder {
var vehicleRiding: Controllable? = null
internal var jumpCounter = 0
internal var walkPowerCounter = 0
@Transient private val MAX_JUMP_LENGTH = 17 // use 17; in internal frames
private var readonly_totalX = 0f
private var readonly_totalY = 0f
internal var jumping = false
internal var walkHeading: Int = 0
@Transient private var prevHMoveKey = KEY_NULL
@Transient private var prevVMoveKey = KEY_NULL
internal var noClip = false
@Transient private val AXIS_POSMAX = 1.0f
@Transient private val GAMEPAD_JUMP = 5
@Transient private val TSIZE = MapDrawer.TILE_SIZE
private val factionSet = HashSet<Faction>()
@Transient private val BASE_DENSITY = 1020
override var referenceID: Long? = PLAYER_REF_ID
/** Must be set by PlayerFactory */
override var inventory: ActorInventory? = null
/** Must be set by PlayerFactory */
override var faction: HashSet<Faction>? = null
override var houseDesignation: ArrayList<Int>? = null
override var luminosity: Char
get() = if (actorValue.get("luminosity") != null) actorValue.getAsInt("luminosity").toChar()
else 0 as Char
set(value) {
actorValue.set("luminosity", value)
}
companion object {
@Transient internal const val ACCEL_MULT_IN_FLIGHT = 0.48f
@Transient internal const val WALK_STOP_ACCEL = 0.32f
@Transient internal const val WALK_ACCEL_BASE = 0.32f
@Transient val PLAYER_REF_ID: Long = 0x51621D
}
/**
* Creates new Player instance with empty elements (sprites, actorvalue, etc.).
* **Use PlayerFactory to build player!**
* @throws SlickException
*/
@Throws(SlickException::class)
constructor() : super() {
isVisible = true
super.setDensity(BASE_DENSITY)
}
override fun update(gc: GameContainer, delta_t: Int) {
if (vehicleRiding is Player)
throw RuntimeException("Attempted to 'ride' " + "player object.")
updatePhysicalInfos()
super.update(gc, delta_t)
updateSprite(delta_t)
updateMovementControl()
if (noClip) {
grounded = true
}
}
private fun updatePhysicalInfos() {
scale = actorValue.getAsFloat("scale")
mass = actorValue.getAsFloat("basemass") * FastMath.pow(scale, 3f)
if (elasticity != 0f) elasticity = 0f
}
/**
* @param left (even if the game is joypad controlled, you must give valid value)
* *
* @param absAxisVal (set AXIS_POSMAX if keyboard controlled)
*/
private fun walkHorizontal(left: Boolean, absAxisVal: Float) {
//if ((!super.isWalledLeft() && left) || (!super.isWalledRight() && !left)) {
readonly_totalX = veloX +
actorValue.getAsFloat("accel") *
actorValue.getAsFloat("accelmult") *
FastMath.sqrt(scale) *
applyAccelRealism(walkPowerCounter) *
(if (left) -1 else 1).toFloat() *
absAxisVal
veloX = readonly_totalX
if (walkPowerCounter < WALK_FRAMES_TO_MAX_ACCEL) {
walkPowerCounter += 1
}
// Clamp veloX
veloX = absClamp(veloX, actorValue.getAsFloat("speed")
* actorValue.getAsFloat("speedmult")
* FastMath.sqrt(scale))
// Heading flag
if (left)
walkHeading = LEFT
else
walkHeading = RIGHT
//}
}
/**
* @param up (even if the game is joypad controlled, you must give valid value)
* *
* @param absAxisVal (set AXIS_POSMAX if keyboard controlled)
*/
private fun walkVertical(up: Boolean, absAxisVal: Float) {
readonly_totalY = veloY +
actorValue.getAsFloat("accel") *
actorValue.getAsFloat("accelmult") *
FastMath.sqrt(scale) *
applyAccelRealism(walkPowerCounter) *
(if (up) -1 else 1).toFloat() *
absAxisVal
veloY = readonly_totalY
if (walkPowerCounter < WALK_FRAMES_TO_MAX_ACCEL) {
walkPowerCounter += 1
}
// Clamp veloX
veloY = absClamp(veloY, actorValue.getAsFloat("speed")
* actorValue.getAsFloat("speedmult")
* FastMath.sqrt(scale))
}
/**
* For realistic accelerating while walking.
* Naïve 'veloX += 3' is actually like:
* a
* | ------------
* |
* |
* 0+------············ t
* which is unrealistic, so this method tries to introduce some realism by doing:
* a
* | ------------
* | ---
* | -
* | ---
* 0+----··················· t
* @param x
*/
private fun applyAccelRealism(x: Int): Float {
return 0.5f + 0.5f * -FastMath.cos(10 * x / (WALK_FRAMES_TO_MAX_ACCEL * FastMath.PI))
}
private fun walkHStop() {
if (veloX > 0) {
veloX -= actorValue.getAsFloat("accel") *
actorValue.getAsFloat("accelmult") *
FastMath.sqrt(scale)
// compensate overshoot
if (veloX < 0) veloX = 0f
} else if (veloX < 0) {
veloX += actorValue.getAsFloat("accel") *
actorValue.getAsFloat("accelmult") *
FastMath.sqrt(scale)
// compensate overshoot
if (veloX > 0) veloX = 0f
} else {
veloX = 0f
}
walkPowerCounter = 0
}
private fun walkVStop() {
if (veloY > 0) {
veloY -= WALK_STOP_ACCEL *
actorValue.getAsFloat("accelmult") *
FastMath.sqrt(scale)
// compensate overshoot
if (veloY < 0)
veloY = 0f
} else if (veloY < 0) {
veloY += WALK_STOP_ACCEL *
actorValue.getAsFloat("accelmult") *
FastMath.sqrt(scale)
// compensate overshoot
if (veloY > 0) veloY = 0f
} else {
veloY = 0f
}
walkPowerCounter = 0
}
private fun updateMovementControl() {
if (!noClip) {
if (grounded) {
actorValue.set("accelmult", 1f)
} else {
actorValue.set("accelmult", ACCEL_MULT_IN_FLIGHT)
}
} else {
actorValue.set("accelmult", 1f)
}
}
override fun processInput(input: Input) {
var gamepad: Controller? = null
var axisX = 0f
var axisY = 0f
var axisRX = 0f
var axisRY = 0f
if (Terrarum.hasController) {
gamepad = Controllers.getController(0)
axisX = gamepad!!.getAxisValue(0)
axisY = gamepad.getAxisValue(1)
axisRX = gamepad.getAxisValue(2)
axisRY = gamepad.getAxisValue(3)
if (Math.abs(axisX) < Terrarum.CONTROLLER_DEADZONE) axisX = 0f
if (Math.abs(axisY) < Terrarum.CONTROLLER_DEADZONE) axisY = 0f
if (Math.abs(axisRX) < Terrarum.CONTROLLER_DEADZONE) axisRX = 0f
if (Math.abs(axisRY) < Terrarum.CONTROLLER_DEADZONE) axisRY = 0f
}
/**
* L-R stop
*/
if (Terrarum.hasController) {
if (axisX == 0f) {
walkHStop()
}
} else {
// ↑F, ↑S
if (!isFuncDown(input, EnumKeyFunc.MOVE_LEFT) && !isFuncDown(input, EnumKeyFunc.MOVE_RIGHT)) {
walkHStop()
prevHMoveKey = KEY_NULL
}
}
/**
* U-D stop
*/
if (Terrarum.hasController) {
if (axisY == 0f) {
walkVStop()
}
} else {
// ↑E
// ↑D
if (isNoClip()
&& !isFuncDown(input, EnumKeyFunc.MOVE_UP)
&& !isFuncDown(input, EnumKeyFunc.MOVE_DOWN)) {
walkVStop()
prevVMoveKey = KEY_NULL
}
}
/**
* Left/Right movement
*/
if (Terrarum.hasController) {
if (axisX != 0f) {
walkHorizontal(axisX < 0, AXIS_POSMAX)
}
} else {
// ↑F, ↓S
if (isFuncDown(input, EnumKeyFunc.MOVE_RIGHT) && !isFuncDown(input, EnumKeyFunc.MOVE_LEFT)) {
walkHorizontal(false, AXIS_POSMAX)
prevHMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_RIGHT)
} else if (isFuncDown(input, EnumKeyFunc.MOVE_LEFT) && !isFuncDown(input, EnumKeyFunc.MOVE_RIGHT)) {
walkHorizontal(true, AXIS_POSMAX)
prevHMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_LEFT)
} else if (isFuncDown(input, EnumKeyFunc.MOVE_LEFT) && isFuncDown(input, EnumKeyFunc.MOVE_RIGHT)) {
if (prevHMoveKey == KeyMap.getKeyCode(EnumKeyFunc.MOVE_LEFT)) {
walkHorizontal(false, AXIS_POSMAX)
prevHMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_RIGHT)
} else if (prevHMoveKey == KeyMap.getKeyCode(EnumKeyFunc.MOVE_RIGHT)) {
walkHorizontal(true, AXIS_POSMAX)
prevHMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_LEFT)
}
}// ↓F, ↓S
// ↓F, ↑S
}
/**
* Up/Down movement
*/
if (noClip) {
if (Terrarum.hasController) {
if (axisY != 0f) {
walkVertical(axisY > 0, AXIS_POSMAX)
}
} else {
// ↑E
// ↓D
if (isFuncDown(input, EnumKeyFunc.MOVE_DOWN) && !isFuncDown(input, EnumKeyFunc.MOVE_UP)) {
walkVertical(false, AXIS_POSMAX)
prevVMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_DOWN)
} else if (isFuncDown(input, EnumKeyFunc.MOVE_UP) && !isFuncDown(input, EnumKeyFunc.MOVE_DOWN)) {
walkVertical(true, AXIS_POSMAX)
prevVMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_UP)
} else if (isFuncDown(input, EnumKeyFunc.MOVE_UP) && isFuncDown(input, EnumKeyFunc.MOVE_DOWN)) {
if (prevVMoveKey == KeyMap.getKeyCode(EnumKeyFunc.MOVE_UP)) {
walkVertical(false, AXIS_POSMAX)
prevVMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_DOWN)
} else if (prevVMoveKey == KeyMap.getKeyCode(EnumKeyFunc.MOVE_DOWN)) {
walkVertical(true, AXIS_POSMAX)
prevVMoveKey = KeyMap.getKeyCode(EnumKeyFunc.MOVE_UP)
}
}// ↓E
// ↓D
// ↓E
// ↑D
}
}
/**
* Jump control
*/
if (isFuncDown(input, EnumKeyFunc.JUMP) || Terrarum.hasController && gamepad!!.isButtonPressed(GAMEPAD_JUMP)) {
if (!noClip) {
if (grounded) {
jumping = true
}
jump()
} else {
walkVertical(true, AXIS_POSMAX)
}
} else {
jumping = false
jumpCounter = 0
}
}
override fun keyPressed(key: Int, c: Char) {
}
/**
* See ./work_files/Jump\ power\ by\ pressing\ time.gcx
*/
private fun jump() {
if (jumping) {
val len = MAX_JUMP_LENGTH.toFloat()
val pwr = actorValue.getAsFloat("jumppower")
// increment jump counter
if (jumpCounter < len) jumpCounter += 1
// quadratic time (convex) mode
/*
float sumT = (jumpCounter * (jumpCounter + 1)) / 2f;
float timedJumpCharge = ((len + 1) / 2f) - (sumT / len);
if (timedJumpCharge < 0) timedJumpCharge = 0;
float jumpAcc = pwr * timedJumpCharge * JUMP_ACCELERATION_MOD;
super.setVeloY(veloY
- jumpAcc
);
*/
// linear time mode
val init = (len + 1) / 2f
var timedJumpCharge = init - init / len * jumpCounter
if (timedJumpCharge < 0) timedJumpCharge = 0f
val jumpAcc = pwr * timedJumpCharge * JUMP_ACCELERATION_MOD * FastMath.sqrt(scale)
veloY -= jumpAcc
// concave mode?
}
// for mob AI:
//super.setVeloY(veloY
// -
// pwr * FastMath.sqrt(scale)
//);
}
private fun jumpFuncLin(pwr: Float, len: Float): Float {
return -(pwr / len) * jumpCounter
}
private fun jumpFuncSqu(pwr: Float, len: Float): Float {
return pwr / (len * len) * (jumpCounter - len * jumpCounter - len) - pwr
}
private fun jumpFuncExp(pwr: Float, len: Float): Float {
val a = FastMath.pow(pwr + 1, 1 / len)
return -FastMath.pow(a, len) + 1
}
private fun isFuncDown(input: Input, fn: EnumKeyFunc): Boolean {
return input.isKeyDown(KeyMap.getKeyCode(fn))
}
private fun absClamp(i: Float, ceil: Float): Float {
if (i > 0)
return if (i > ceil) ceil else i
else if (i < 0)
return if (-i > ceil) -ceil else i
else
return 0f
}
private fun updateSprite(delta_t: Int) {
sprite!!.update(delta_t)
if (spriteGlow != null) {
spriteGlow!!.update(delta_t)
}
if (grounded) {
if (walkHeading == LEFT) {
sprite!!.flip(true, false)
if (spriteGlow != null) {
spriteGlow!!.flip(true, false)
}
} else {
sprite!!.flip(false, false)
if (spriteGlow != null) {
spriteGlow!!.flip(false, false)
}
}
}
}
fun isNoClip(): Boolean {
return noClip
}
fun setNoClip(b: Boolean) {
noClip = b
}
fun getActorValue(): ActorValue {
return actorValue
}
override fun assignFaction(f: Faction) {
factionSet.add(f)
}
override fun unassignFaction(f: Faction) {
factionSet.remove(f)
}
override fun addHouseTile(x: Int, y: Int) {
throw UnsupportedOperationException()
}
override fun removeHouseTile(x: Int, y: Int) {
throw UnsupportedOperationException()
}
override fun clearHouseDesignation() {
throw UnsupportedOperationException()
}
}

View File

@@ -38,7 +38,7 @@ public class PlayerDebugger {
public float scale() { return getPlayer().getScale(); }
public Hitbox hitbox() { return getPlayer().getHitbox(); }
public Hitbox nextHitbox() { return getPlayer().getNextHitbox(); }
public boolean grounded() { return getPlayer().isGrounded(); }
public boolean grounded() { return getPlayer().getGrounded(); }
public ActorValue actorValue() { return getPlayer().getActorValue(); }
public float mass() { return getPlayer().getMass(); }
public boolean noClip() { return getPlayer().isNoClip(); }

View File

@@ -8,13 +8,13 @@ import java.io.IOException;
/**
* Created by minjaesong on 16-02-03.
*/
public class PlayerBuildFactory {
public class PlayerFactory {
private static final String JSONPATH = "./res/raw/";
private static String jsonString = new String();
public Player build(String jsonFileName) throws IOException, SlickException {
Player p = (Player) (new CreatureBuildFactory().build("CreatureHuman"));
Player p = (Player) (new CreatureFactory().build("CreatureHuman"));
// attach sprite

View File

@@ -1,12 +0,0 @@
package com.Torvald.Terrarum.Actors;
/**
* Created by minjaesong on 16-01-15.
*/
public interface Pocketed {
public ActorInventory getInventory();
public void overwriteInventory(ActorInventory inventory);
}

View File

@@ -0,0 +1,10 @@
package com.Torvald.Terrarum.Actors
/**
* Created by minjaesong on 16-03-14.
*/
interface Pocketed {
var inventory: ActorInventory?
}

View File

@@ -0,0 +1,13 @@
package com.Torvald.Terrarum.Actors
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
/**
* Created by minjaesong on 16-03-14.
*/
interface Visible {
fun drawBody(gc: GameContainer, g: Graphics)
fun updateBodySprite(gc: GameContainer, delta: Int)
}

View File

@@ -2,12 +2,7 @@ package com.Torvald.Terrarum.ConsoleCommand;
import com.Torvald.JsonWriter;
import com.Torvald.Terrarum.Terrarum;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
@@ -18,7 +13,7 @@ public class ExportAV implements ConsoleCommand {
public void execute(String[] args) {
if (args.length == 2) {
try {
JsonWriter.writeFile(Terrarum.game.getPlayer().getActorValue()
JsonWriter.writeToFile(Terrarum.game.getPlayer().getActorValue()
, Terrarum.defaultDir + "/Exports/" + args[1] + ".json"
);

View File

@@ -18,7 +18,7 @@ public class GetFactioning implements ConsoleCommand {
Echo echo = new Echo();
if (args.length == 1) { // get all factioning data of player
HashSet<Faction> factionSet = Terrarum.game.getPlayer().getAssignedFactions();
HashSet<Faction> factionSet = Terrarum.game.getPlayer().getFaction();
int count = factionSet.size();
echo.execute(String.valueOf(count) + Lang.pluralise(" faction", count) + " assigned.");

View File

@@ -1,9 +1,8 @@
package com.Torvald.Terrarum.ConsoleCommand;
import com.Torvald.Terrarum.Game;
import com.Torvald.Terrarum.LangPack.Lang;
import com.Torvald.Terrarum.Terrarum;
import com.Torvald.Terrarum.UserInterface.Bulletin;
import com.Torvald.Terrarum.UserInterface.Notification;
/**
* Created by minjaesong on 16-01-23.
@@ -11,13 +10,10 @@ import com.Torvald.Terrarum.UserInterface.Bulletin;
public class SetBulletin implements ConsoleCommand {
@Override
public void execute(String[] args) {
new Echo().execute(Lang.get("ERROR_SAVE_CORRUPTED")
+ " "
+ Lang.get("MENU_LABEL_CONTINUE_QUESTION"));
String[] testMsg = {
"SetBulletin: this is a test!"
, "게임 내 방송입니다."
//Lang.get("ERROR_SAVE_CORRUPTED")
//, Lang.get("MENU_LABEL_CONTINUE_QUESTION")
"갎갎갎갎갎갎갎갎갎갎갎갎갎갎"
};
send(testMsg);
}
@@ -28,11 +24,11 @@ public class SetBulletin implements ConsoleCommand {
}
/**
* Actually send bulletin
* Actually send notifinator
* @param message real message
*/
public void send(String[] message) {
((Bulletin) (Terrarum.game.bulletin.getUI())).sendBulletin(message);
System.out.println("sent bulletin");
Terrarum.game.sendNotification(message);
System.out.println("sent notifinator");
}
}

View File

@@ -0,0 +1,21 @@
package com.Torvald.Terrarum;
import com.google.gson.JsonObject;
/**
* Created by minjaesong on 16-03-12.
*/
public class DefaultConfig {
public static JsonObject fetch() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("smoothlighting", true);
jsonObject.addProperty("imtooyoungtodie", false);
jsonObject.addProperty("language", Terrarum.getSysLang());
jsonObject.addProperty("notificationshowuptime", 6500);
return jsonObject;
}
}

View File

@@ -5,7 +5,6 @@ import com.Torvald.Terrarum.ConsoleCommand.Authenticator;
import com.Torvald.Terrarum.ConsoleCommand.CommandDict;
import com.Torvald.Terrarum.GameControl.GameController;
import com.Torvald.Terrarum.GameControl.KeyMap;
import com.Torvald.Terrarum.GameControl.KeyToggler;
import com.Torvald.Terrarum.GameMap.GameMap;
import com.Torvald.Terrarum.GameMap.WorldTime;
import com.Torvald.Terrarum.MapDrawer.LightmapRenderer;
@@ -15,6 +14,7 @@ import com.Torvald.Terrarum.MapGenerator.MapGenerator;
import com.Torvald.Terrarum.TileProperties.TilePropCodex;
import com.Torvald.Terrarum.TileStat.TileStat;
import com.Torvald.Terrarum.UserInterface.*;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.*;
import org.newdawn.slick.Graphics;
@@ -24,6 +24,9 @@ import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import shader.Shader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.HashSet;
@@ -36,8 +39,6 @@ public class Game extends BasicGameState {
public static long totalVMMem;
int game_mode = 0;
public GameConfig gameConfig;
public GameMap map;
public HashSet<Actor> actorContainer = new HashSet<>();
@@ -45,7 +46,7 @@ public class Game extends BasicGameState {
public UIHandler consoleHandler;
public UIHandler debugWindow;
public UIHandler bulletin;
public UIHandler notifinator;
@NotNull Player player;
@@ -64,6 +65,11 @@ public class Game extends BasicGameState {
public Game() throws SlickException { }
private boolean useShader;
private int shaderProgram = 0;
@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws
SlickException {
@@ -72,14 +78,11 @@ public class Game extends BasicGameState {
GameController.setKeyMap(new KeyMap());
gameConfig = new GameConfig();
gameConfig.set("smoothlighting", true);
shader12BitCol = Shader.makeShader("./res/4096.vrt", "./res/4096.frg");
shaderBlurH = Shader.makeShader("./res/blurH.vrt", "./res/blur.frg");
shaderBlurV = Shader.makeShader("./res/blurV.vrt", "./res/blur.frg");
GRADIENT_IMAGE = new Image("res/graphics/backgroundGradientColour.png");
skyBox = new Rectangle(0, 0, Terrarum.WIDTH, Terrarum.HEIGHT);
@@ -98,7 +101,7 @@ public class Game extends BasicGameState {
// add new player and put it to actorContainer
//player = new Player();
player = new PBFSigrid().build();
player = new PFSigrid().build();
//player.setNoClip(true);
actorContainer.add(player);
@@ -112,22 +115,13 @@ public class Game extends BasicGameState {
debugWindow = new UIHandler(new BasicDebugInfoWindow());
debugWindow.setPosition(0, 0);
bulletin = new UIHandler(new Bulletin());
bulletin.setPosition(
(Terrarum.WIDTH - bulletin.getUI().getWidth())
notifinator = new UIHandler(new Notification());
notifinator.setPosition(
(Terrarum.WIDTH - notifinator.getUI().getWidth())
/ 2
, 0
, Terrarum.HEIGHT - notifinator.getUI().getHeight()
);
bulletin.setVisibility(true);
UIHandler msgtest = new UIHandler(new Message(400, true));
String[] msg = {"Hello, world!", "안녕, 세상아!"};
((Message) msgtest.getUI()).setMessage(msg);
msgtest.setPosition(32, 32);
// msgtest.setVisibility(true);
uiContainer.add(msgtest);
notifinator.setVisibility(true);
}
public Player getPlayer() {
@@ -159,7 +153,7 @@ public class Game extends BasicGameState {
uiContainer.forEach(ui -> ui.update(gc, delta_t));
//bulletin.update(gc, delta_t);
notifinator.update(gc, delta_t);
Terrarum.appgc.setVSync(Terrarum.appgc.getFPS() >= Terrarum.VSYNC_TRIGGER_THRESHOLD);
}
@@ -212,9 +206,7 @@ public class Game extends BasicGameState {
uiContainer.forEach(ui -> ui.render(gc, g));
debugWindow.render(gc, g);
consoleHandler.render(gc, g);
//bulletin.render(gc, g);
GL11.glEnd();
notifinator.render(gc, g);
}
public boolean addActor(Actor e) {
@@ -294,4 +286,98 @@ public class Game extends BasicGameState {
GL11.glDisable(GL11.GL_BLEND);
Terrarum.appgc.getGraphics().setDrawMode(Graphics.MODE_NORMAL);
}
public void sendNotification(String[] msg) {
((Notification) notifinator.getUI()).sendNotification(msg);
}
private int createShader(String filename, int shaderType) throws Exception {
int shader = 0;
try {
shader = ARBShaderObjects.glCreateShaderObjectARB(shaderType);
if(shader == 0)
return 0;
ARBShaderObjects.glShaderSourceARB(shader, readFileAsString(filename));
ARBShaderObjects.glCompileShaderARB(shader);
if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE)
throw new RuntimeException("Error creating shader: " + getLogInfo(shader));
return shader;
}
catch(Exception exc) {
ARBShaderObjects.glDeleteObjectARB(shader);
throw exc;
}
}
private static String getLogInfo(int obj) {
return ARBShaderObjects.glGetInfoLogARB(obj, ARBShaderObjects.glGetObjectParameteriARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB));
}
private String readFileAsString(String filename) throws Exception {
StringBuilder source = new StringBuilder();
FileInputStream in = new FileInputStream(filename);
Exception exception = null;
BufferedReader reader;
try{
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
Exception innerExc= null;
try {
String line;
while((line = reader.readLine()) != null)
source.append(line).append('\n');
}
catch(Exception exc) {
exception = exc;
}
finally {
try {
reader.close();
}
catch(Exception exc) {
if(innerExc == null)
innerExc = exc;
else
exc.printStackTrace();
}
}
if(innerExc != null)
throw innerExc;
}
catch(Exception exc) {
exception = exc;
}
finally {
try {
in.close();
}
catch(Exception exc) {
if(exception == null)
exception = exc;
else
exc.printStackTrace();
}
if(exception != null)
throw exception;
}
return source.toString();
}
public long getMemInUse() {
return memInUse;
}
public long getTotalVMMem() {
return totalVMMem;
}
}

View File

@@ -36,8 +36,8 @@ public class GameController {
if (!Terrarum.game.consoleHandler.isTakingControl()) {
if (Terrarum.game.getPlayer().vehicleRiding != null) {
Terrarum.game.getPlayer().vehicleRiding.processInput(input);
if (Terrarum.game.getPlayer().getVehicleRiding() != null) {
Terrarum.game.getPlayer().getVehicleRiding().processInput(input);
}
Terrarum.game.getPlayer().processInput(input);
@@ -82,8 +82,8 @@ public class GameController {
if (!Terrarum.game.consoleHandler.isTakingControl()) {
if (Terrarum.game.getPlayer().vehicleRiding != null) {
Terrarum.game.getPlayer().vehicleRiding.keyPressed(key, c);
if (Terrarum.game.getPlayer().getVehicleRiding() != null) {
Terrarum.game.getPlayer().getVehicleRiding().keyPressed(key, c);
}
Terrarum.game.getPlayer().keyPressed(key, c);

View File

@@ -1,5 +1,7 @@
package com.Torvald.Terrarum;
import com.google.gson.JsonPrimitive;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Set;
@@ -44,15 +46,20 @@ public class KVHashMap {
public float getAsFloat(String key) {
Object value = get(key);
if (value instanceof Integer) return ((Integer) value).floatValue();
else return (float) value;
else if (value instanceof JsonPrimitive) return ((JsonPrimitive) value).getAsFloat();
return (float) value;
}
public String getAsString(String key) {
return (String) get(key);
Object value = get(key);
if (value instanceof JsonPrimitive) return ((JsonPrimitive) value).getAsString();
return (String) value;
}
public boolean getAsBoolean(String key) {
return (boolean) get(key);
Object value = get(key);
if (value instanceof JsonPrimitive) return ((JsonPrimitive) value).getAsBoolean();
return (boolean) value;
}
public boolean hasKey(String key) {

View File

@@ -155,8 +155,8 @@ public class LightmapRenderer {
for (int y = for_y_start; y < for_y_end; y++) {
for (int x = for_x_start; x < for_x_end; x++) {
// smooth
if (Terrarum.game.screenZoom >= 1 && ((boolean) Terrarum.game.gameConfig.get(
"smoothlighting"))) {
if (Terrarum.game.screenZoom >= 1
&& Terrarum.gameConfig.getAsBoolean("smoothlighting")) {
char thisLightLevel = staticLightMap[y][x];
if (y > 0 && x < for_x_end && thisLightLevel == 0 && staticLightMap[y - 1][x] == 0) {
try {
@@ -317,7 +317,7 @@ public class LightmapRenderer {
int tileX = Math.round(actorBody.getHitbox().getPointedX() / TSIZE);
int tileY = Math.round(actorBody.getHitbox().getPointedY() / TSIZE)
- 1;
char actorLuminosity = actorLum.getLuminance();
char actorLuminosity = actorLum.getLuminosity();
if (x == tileX && y == tileY) {
lightLevelThis = screenBlend(lightLevelThis, actorLuminosity);
}

View File

@@ -71,6 +71,22 @@ public class MapCamera {
, TileNameCode.ILLUMINATOR_TAN
, TileNameCode.ILLUMINATOR_WHITE
, TileNameCode.ILLUMINATOR_YELLOW
, TileNameCode.ILLUMINATOR_BLACK_OFF
, TileNameCode.ILLUMINATOR_BLUE_OFF
, TileNameCode.ILLUMINATOR_BROWN_OFF
, TileNameCode.ILLUMINATOR_CYAN_OFF
, TileNameCode.ILLUMINATOR_FUCHSIA_OFF
, TileNameCode.ILLUMINATOR_GREEN_OFF
, TileNameCode.ILLUMINATOR_GREEN_DARK_OFF
, TileNameCode.ILLUMINATOR_GREY_DARK_OFF
, TileNameCode.ILLUMINATOR_GREY_LIGHT_OFF
, TileNameCode.ILLUMINATOR_GREY_MED_OFF
, TileNameCode.ILLUMINATOR_ORANGE_OFF
, TileNameCode.ILLUMINATOR_PURPLE_OFF
, TileNameCode.ILLUMINATOR_RED_OFF
, TileNameCode.ILLUMINATOR_TAN_OFF
, TileNameCode.ILLUMINATOR_WHITE_OFF
, TileNameCode.ILLUMINATOR_YELLOW
, TileNameCode.SANDSTONE
, TileNameCode.SANDSTONE_BLACK
, TileNameCode.SANDSTONE_DESERT
@@ -376,9 +392,12 @@ public class MapCamera {
// try for
int ret = 0;
for (int i = 0; i < 4; i++) {
if (!TilePropCodex.getProp(nearbyTiles[i]).isSolid()) {
ret += (1 << i); // add 1, 2, 4, 8 for i = 0, 1, 2, 3
try {
if (!TilePropCodex.getProp(nearbyTiles[i]).isSolid()) {
ret += (1 << i); // add 1, 2, 4, 8 for i = 0, 1, 2, 3
}
}
catch (ArrayIndexOutOfBoundsException e) {}
}
return ret;

View File

@@ -8,11 +8,10 @@
Byte[n] name Savegame name, UTF-8
Byte null String terminator
Byte[8] terraseed Terrain seed
Byte[8] <arb name> possible other seeds
Byte[8] rogueseed Randomiser seed
Byte[32] hash1 SHA-256 hash of worldinfo1 being stored
Byte[32] hash2 SHA-256 hash of worldinfo2 being stored
Byte[32] hash3 SHA-256 hash of worldinfo3 being stored
Byte[32] hash4 SHA-256 hash of worldinfo4 beihg stored (TEMD data) [32, 214, 42, 3, 76, ...]
Byte[32] hash4 SHA-256 hash of worldinfo3 beihg stored (TEMD data) [32, 214, 42, 3, 76, ...]
* Actor data
@@ -51,5 +50,4 @@
--- world save meta
--- worldinfo1 tileprop
--- worldinfo2 itemprop
--- worldinfo3 Roguelike randomiser
--- worldinfo4 TEMD binary
--- worldinfo3 TEMD binary

View File

@@ -1,17 +1,15 @@
package com.Torvald.Terrarum;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.Torvald.ImageFont.GameFontBase;
import com.Torvald.ImageFont.GameFontWhite;
import com.Torvald.JsonFetcher;
import com.Torvald.JsonWriter;
import com.Torvald.Terrarum.LangPack.Lang;
import com.google.gson.JsonObject;
import org.lwjgl.input.Controllers;
import org.newdawn.slick.*;
import org.newdawn.slick.state.StateBasedGame;
@@ -43,6 +41,7 @@ public class Terrarum extends StateBasedGame {
public static final int VSYNC_TRIGGER_THRESHOLD = 56;
public static Game game;
public static GameConfig gameConfig;
public static String OSName;
public static String OSVersion;
@@ -60,31 +59,25 @@ public class Terrarum extends StateBasedGame {
public static boolean hasController = false;
public static final float CONTROLLER_DEADZONE = 0.1f;
private static String configDir;
public Terrarum(String gamename) throws SlickException {
super(gamename);
gameConfig = new GameConfig();
getDefaultDirectory();
createDirs();
try {
createFiles();
}
catch (IOException e) {
e.printStackTrace();
}
// TODO if config language is not defined
if (gameLocale.length() < 2) { // get system language if not overridden
String lan = System.getProperty("user.language");
String country = System.getProperty("user.country");
boolean readFromDisk = readConfigJson();
if (!readFromDisk) readConfigJson();
// exception handling
if (lan.equals("en")) country = "US";
else if (lan.equals("fr")) country = "FR";
else if (lan.equals("de")) country = "DE";
else if (lan.equals("ko")) country = "KR";
// get locale from config
gameLocale = gameConfig.getAsString("language");
gameLocale = lan + country;
}
// if game locale were not set, use system locale
if (gameLocale.length() < 4)
gameLocale = getSysLang();
System.out.println("[Terrarum] Locale: " + gameLocale);
}
@@ -160,6 +153,7 @@ public class Terrarum extends StateBasedGame {
}
defaultSaveDir = defaultDir + "/Saves";
configDir = defaultDir + "/config.json";
}
private static void createDirs(){
@@ -174,15 +168,138 @@ public class Terrarum extends StateBasedGame {
}
}
private static void createFiles() throws IOException {
File configFile = new File(defaultDir + "/config.json");
private static void createConfigJson() throws IOException {
File configFile = new File(configDir);
if (!configFile.exists() || configFile.length() == 0) {
configFile.createNewFile();
ArrayList<String> jsonLines = JsonFetcher.readJsonAsString("./res/config_default.json");
PrintWriter printWriter = new PrintWriter(configFile);
jsonLines.forEach(printWriter::println);
printWriter.close();
JsonWriter.writeToFile(DefaultConfig.fetch(), configDir);
}
}
private static boolean readConfigJson() {
try {
// read from disk and build config from it
JsonObject jsonObject = JsonFetcher.readJson(configDir);
// make config
jsonObject.entrySet().forEach(
entry -> gameConfig.set(entry.getKey(), entry.getValue())
);
return true;
}
catch (IOException e) {
// write default config to game dir. Call this method again to read config from it.
try {
createConfigJson();
}
catch (IOException e1) {
e.printStackTrace();
}
return false;
}
}
public static String getSysLang() {
String lan = System.getProperty("user.language");
String country = System.getProperty("user.country");
// exception handling
if (lan.equals("en")) country = "US";
else if (lan.equals("fr")) country = "FR";
else if (lan.equals("de")) country = "DE";
else if (lan.equals("ko")) country = "KR";
return lan + country;
}
/**
* Return config from config set. If the config does not exist, default value will be returned.
* @param key
* @return Config from config set or default config if it does not exist.
* @throws NullPointerException if the specified config simply does not exist.
*/
public static int getConfigInt(String key) {
int cfg = 0;
try {
cfg = gameConfig.getAsInt(key);
}
catch (NullPointerException e) {
try {
cfg = DefaultConfig.fetch().get(key).getAsInt();
}
catch (NullPointerException e1) {
e.printStackTrace();
}
}
return cfg;
}
/**
* Return config from config set. If the config does not exist, default value will be returned.
* @param key
* @return Config from config set or default config if it does not exist.
* @throws NullPointerException if the specified config simply does not exist.
*/
public static float getConfigFloat(String key) {
float cfg = 0;
try {
cfg = gameConfig.getAsFloat(key);
}
catch (NullPointerException e) {
try {
cfg = DefaultConfig.fetch().get(key).getAsFloat();
}
catch (NullPointerException e1) {
e.printStackTrace();
}
}
return cfg;
}
/**
* Return config from config set. If the config does not exist, default value will be returned.
* @param key
* @return Config from config set or default config if it does not exist.
* @throws NullPointerException if the specified config simply does not exist.
*/
public static String getConfigString(String key) {
String cfg = "";
try {
cfg = gameConfig.getAsString(key);
}
catch (NullPointerException e) {
try {
cfg = DefaultConfig.fetch().get(key).getAsString();
}
catch (NullPointerException e1) {
e.printStackTrace();
}
}
return cfg;
}
/**
* Return config from config set. If the config does not exist, default value will be returned.
* @param key
* @return Config from config set or default config if it does not exist.
* @throws NullPointerException if the specified config simply does not exist.
*/
public static boolean getConfigBoolean(String key) {
boolean cfg = false;
try {
cfg = gameConfig.getAsBoolean(key);
}
catch (NullPointerException e) {
try {
cfg = DefaultConfig.fetch().get(key).getAsBoolean();
}
catch (NullPointerException e1) {
e.printStackTrace();
}
}
return cfg;
}
}

View File

@@ -83,12 +83,29 @@ public class TileNameCode {
public static final int ILLUMINATOR_GREY_DARK = TilePropCodex.indexDamageToArrayAddr(13, 14);
public static final int ILLUMINATOR_BLACK = TilePropCodex.indexDamageToArrayAddr(13, 15);
public static final int SANDSTONE = TilePropCodex.indexDamageToArrayAddr(14, 0);
public static final int SANDSTONE_WHITE = TilePropCodex.indexDamageToArrayAddr(14, 1);
public static final int SANDSTONE_RED = TilePropCodex.indexDamageToArrayAddr(14, 2);
public static final int SANDSTONE_DESERT = TilePropCodex.indexDamageToArrayAddr(14, 3);
public static final int SANDSTONE_BLACK = TilePropCodex.indexDamageToArrayAddr(14, 4);
public static final int SANDSTONE_GREEN = TilePropCodex.indexDamageToArrayAddr(14, 5);
public static final int ILLUMINATOR_WHITE_OFF = TilePropCodex.indexDamageToArrayAddr(14, 0);
public static final int ILLUMINATOR_YELLOW_OFF = TilePropCodex.indexDamageToArrayAddr(14, 1);
public static final int ILLUMINATOR_ORANGE_OFF = TilePropCodex.indexDamageToArrayAddr(14, 2);
public static final int ILLUMINATOR_RED_OFF = TilePropCodex.indexDamageToArrayAddr(14, 3);
public static final int ILLUMINATOR_FUCHSIA_OFF = TilePropCodex.indexDamageToArrayAddr(14, 4);
public static final int ILLUMINATOR_PURPLE_OFF = TilePropCodex.indexDamageToArrayAddr(14, 5);
public static final int ILLUMINATOR_BLUE_OFF = TilePropCodex.indexDamageToArrayAddr(14, 6);
public static final int ILLUMINATOR_CYAN_OFF = TilePropCodex.indexDamageToArrayAddr(14, 7);
public static final int ILLUMINATOR_GREEN_OFF = TilePropCodex.indexDamageToArrayAddr(14, 8);
public static final int ILLUMINATOR_GREEN_DARK_OFF = TilePropCodex.indexDamageToArrayAddr(14, 9);
public static final int ILLUMINATOR_BROWN_OFF = TilePropCodex.indexDamageToArrayAddr(14, 10);
public static final int ILLUMINATOR_TAN_OFF = TilePropCodex.indexDamageToArrayAddr(14, 11);
public static final int ILLUMINATOR_GREY_LIGHT_OFF = TilePropCodex.indexDamageToArrayAddr(14, 12);
public static final int ILLUMINATOR_GREY_MED_OFF = TilePropCodex.indexDamageToArrayAddr(14, 13);
public static final int ILLUMINATOR_GREY_DARK_OFF = TilePropCodex.indexDamageToArrayAddr(14, 14);
public static final int ILLUMINATOR_BLACK_OFF = TilePropCodex.indexDamageToArrayAddr(14, 15);
public static final int SANDSTONE = TilePropCodex.indexDamageToArrayAddr(15, 0);
public static final int SANDSTONE_WHITE = TilePropCodex.indexDamageToArrayAddr(15, 1);
public static final int SANDSTONE_RED = TilePropCodex.indexDamageToArrayAddr(15, 2);
public static final int SANDSTONE_DESERT = TilePropCodex.indexDamageToArrayAddr(15, 3);
public static final int SANDSTONE_BLACK = TilePropCodex.indexDamageToArrayAddr(15, 4);
public static final int SANDSTONE_GREEN = TilePropCodex.indexDamageToArrayAddr(15, 5);
public static final int WATER_1 = TilePropCodex.indexDamageToArrayAddr(254, 0);
public static final int WATER_2 = TilePropCodex.indexDamageToArrayAddr(254, 1);

View File

@@ -60,13 +60,29 @@
"13"; "12";"TILE_ILLUMINATOR_GREY_LIGHT"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "47589"; "13"; "12"; "0";"16"
"13"; "13";"TILE_ILLUMINATOR_GREY_MED"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "29538"; "13"; "13"; "0";"16"
"13"; "14";"TILE_ILLUMINATOR_GREY_DARK"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "16410"; "13"; "14"; "0";"16"
"13"; "15";"TILE_ILLUMINATOR_BLACK" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "4923"; "13"; "15"; "0";"16"
"14"; "0";"TILE_SANDSTONE" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "14"; "0"; "0";"16"
"14"; "1";"TILE_SANDSTONE_WHITE" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "14"; "1"; "0";"16"
"14"; "2";"TILE_SANDSTONE_RED" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "14"; "2"; "0";"16"
"14"; "3";"TILE_SANDSTONE_DESERT" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "14"; "3"; "0";"16"
"14"; "4";"TILE_SANDSTONE_BLACK" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "14"; "4"; "0";"16"
"14"; "5";"TILE_SANDSTONE_BLACK" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "14"; "5"; "0";"16"
"13"; "15";"TILE_ILLUMINATOR_BLACK" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "27239"; "13"; "15"; "0";"16"
"14"; "0";"TILE_ILLUMINATOR_WHITE" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "0"; "0";"16"
"14"; "1";"TILE_ILLUMINATOR_YELLOW" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "1"; "0";"16"
"14"; "2";"TILE_ILLUMINATOR_ORANGE" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "2"; "0";"16"
"14"; "3";"TILE_ILLUMINATOR_RED" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "3"; "0";"16"
"14"; "4";"TILE_ILLUMINATOR_FUCHSIA" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "4"; "0";"16"
"14"; "5";"TILE_ILLUMINATOR_PURPLE" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "5"; "0";"16"
"14"; "6";"TILE_ILLUMINATOR_BLUE" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "6"; "0";"16"
"14"; "7";"TILE_ILLUMINATOR_CYAN" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "7"; "0";"16"
"14"; "8";"TILE_ILLUMINATOR_GREEN" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "8"; "0";"16"
"14"; "9";"TILE_ILLUMINATOR_GREEN_DARK"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "9"; "0";"16"
"14"; "10";"TILE_ILLUMINATOR_BROWN" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "10"; "0";"16"
"14"; "11";"TILE_ILLUMINATOR_TAN" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "11"; "0";"16"
"14"; "12";"TILE_ILLUMINATOR_GREY_LIGHT"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "12"; "0";"16"
"14"; "13";"TILE_ILLUMINATOR_GREY_MED"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "13"; "0";"16"
"14"; "14";"TILE_ILLUMINATOR_GREY_DARK"; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "14"; "0";"16"
"14"; "15";"TILE_ILLUMINATOR_BLACK" ; "0"; "0"; "N/A"; "0"; "0"; "1"; "1"; "0"; "13"; "15"; "0";"16"
"15"; "0";"TILE_SANDSTONE" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "0"; "0";"16"
"15"; "1";"TILE_SANDSTONE_WHITE" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "1"; "0";"16"
"15"; "2";"TILE_SANDSTONE_RED" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "2"; "0";"16"
"15"; "3";"TILE_SANDSTONE_DESERT" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "3"; "0";"16"
"15"; "4";"TILE_SANDSTONE_BLACK" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "4"; "0";"16"
"15"; "5";"TILE_SANDSTONE_BLACK" ; "8205"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "5"; "0";"16"
"254"; "0";"TILE_WATER" ; "6522"; "100";"1000"; "1"; "12"; "0"; "0"; "0"; "N/A"; "N/A"; "0";"16"
"254"; "1";"TILE_WATER" ; "6522"; "100";"1000"; "1"; "12"; "0"; "0"; "0"; "N/A"; "N/A"; "0";"16"
"254"; "2";"TILE_WATER" ; "6522"; "100";"1000"; "1"; "12"; "0"; "0"; "0"; "N/A"; "N/A"; "0";"16"
@@ -111,6 +127,8 @@
# Magical ice: theoretical __metallic__ ice that might form under super-high pressure (> 5 TPa). Its density is a wild guess.
# Off illuminator: NO OPACITY! this is intended!
# References:
# * Density of various woods : http://www.engineeringtoolbox.com/wood-density-d_40.html
# * Density of various phases of ice : http://www1.lsbu.ac.uk/water/ice_phases.html
Can't render this file because it contains an unexpected character in line 1 and column 18.

View File

@@ -0,0 +1,150 @@
package com.Torvald.Terrarum.UserInterface
import com.Torvald.Terrarum.GameMap.PairedMapLayer
import com.Torvald.Terrarum.LangPack.Lang
import com.Torvald.Terrarum.MapDrawer.LightmapRenderer
import com.Torvald.Terrarum.MapDrawer.MapCamera
import com.Torvald.Terrarum.MapDrawer.MapDrawer
import com.Torvald.Terrarum.Terrarum
import org.newdawn.slick.Color
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
import org.newdawn.slick.Input
import java.util.*
/**
* Created by minjaesong on 16-03-14.
*/
class BasicDebugInfoWindow : UICanvas {
override var width: Int? = Terrarum.WIDTH
override var height: Int? = Terrarum.HEIGHT
override fun processInput(input: Input) {
}
override fun update(gc: GameContainer, delta_t: Int) {
}
override fun render(gc: GameContainer, g: Graphics) {
val player = Terrarum.game.player
val sb = StringBuilder()
val formatter = Formatter(sb)
val mouseTileX = ((MapCamera.getCameraX() + gc.getInput().mouseX / Terrarum.game.screenZoom) / MapDrawer.TILE_SIZE).toInt()
val mouseTileY = ((MapCamera.getCameraY() + gc.getInput().mouseY / Terrarum.game.screenZoom) / MapDrawer.TILE_SIZE).toInt()
g.setColor(Color.white)
val hitbox = player.hitbox
val nextHitbox = player.nextHitbox
printLine(g, 1, "posX : "
+ "${hitbox!!.pointedX.toString()}"
+ " ("
+ "${(hitbox!!.pointedX / MapDrawer.TILE_SIZE).toInt().toString()}"
+ ")")
printLine(g, 2, "posY : "
+ hitbox.pointedY.toString()
+ " ("
+ (hitbox.pointedY / MapDrawer.TILE_SIZE).toInt().toString()
+ ")")
printLine(g, 3, "veloX : ${player.veloX}")
printLine(g, 4, "veloY : ${player.veloY}")
printLine(g, 5, "grounded : ${player.grounded}")
printLine(g, 6, "noClip : ${player.noClip}")
printLine(g, 7, "mass : ${player.mass} [kg]")
val lightVal: String
var mtX = mouseTileX.toString()
var mtY = mouseTileY.toString()
try {
val valRaw = LightmapRenderer.getValueFromMap(mouseTileX, mouseTileY)
val rawR = LightmapRenderer.getRawR(valRaw)
val rawG = LightmapRenderer.getRawG(valRaw)
val rawB = LightmapRenderer.getRawB(valRaw)
lightVal = valRaw.toInt().toString() + " (" +
rawR.toString() + " " +
rawG.toString() + " " +
rawB.toString() + ")"
} catch (e: ArrayIndexOutOfBoundsException) {
lightVal = "out of bounds"
mtX = "---"
mtY = "---"
}
printLine(g, 8, "light at cursor : " + lightVal)
val tileNo: String
try {
val tileNumRaw = Terrarum.game.map.getTileFromTerrain(mouseTileX, mouseTileY)
val tilenum = tileNumRaw / PairedMapLayer.RANGE
val tiledmg = tileNumRaw % PairedMapLayer.RANGE
tileNo = "$tilenum:$tiledmg"
} catch (e: ArrayIndexOutOfBoundsException) {
tileNo = "-"
}
printLine(g, 9, "tile : $tileNo ($mtX, $mtY)")
/**
* Second column
*/
printLineColumn(g, 2, 1, "Vsync : " + Terrarum.appgc.isVSyncRequested)
printLineColumn(g, 2, 2, "Env colour temp : " + MapDrawer.getColTemp())
/**
* On screen
*/
// Memory allocation
val memInUse = Terrarum.game.memInUse
val totalVMMem = Terrarum.game.totalVMMem
g.setColor(Color(0xFF7F00))
g.drawString(
Lang.get("DEV_MEMORY_SHORT_CAP")
+ " : "
+ formatter.format(
Lang.get("DEV_MEMORY_A_OF_B"), memInUse, totalVMMem), (Terrarum.WIDTH - 200).toFloat(), line(1).toFloat())
// Hitbox
val zoom = Terrarum.game.screenZoom
g.setColor(Color(0x007f00))
g.drawRect(hitbox.getHitboxStart().getX() * zoom - MapCamera.getCameraX() * zoom, hitbox.getHitboxStart().getY() * zoom - MapCamera.getCameraY() * zoom, hitbox.getWidth() * zoom, hitbox.getHeight() * zoom)
// ...and its point
g.fillRect(
(hitbox.getPointedX() - 1) * zoom - MapCamera.getCameraX() * zoom, (hitbox.getPointedY() - 1) * zoom - MapCamera.getCameraY() * zoom, 3f, 3f)
g.drawString(
Lang.get("DEV_COLOUR_LEGEND_GREEN") + " : hitbox", (Terrarum.WIDTH - 200).toFloat(), line(2).toFloat())
// Next hitbox
g.setColor(Color.blue)
g.drawRect(nextHitbox!!.getHitboxStart().getX() * zoom - MapCamera.getCameraX() * zoom, nextHitbox.getHitboxStart().getY() * zoom - MapCamera.getCameraY() * zoom, nextHitbox.getWidth() * zoom, nextHitbox.getHeight() * zoom)
// ...and its point
g.fillRect(
(nextHitbox!!.getPointedX() - 1) * zoom - MapCamera.getCameraX() * zoom, (nextHitbox.getPointedY() - 1) * zoom - MapCamera.getCameraY() * zoom, 3f, 3f)
g.drawString(
Lang.get("DEV_COLOUR_LEGEND_BLUE") + " : nextHitbox", (Terrarum.WIDTH - 200).toFloat(), line(3).toFloat())
}
private fun printLine(g: Graphics, l: Int, s: String) {
g.drawString(s, 20f, line(l).toFloat())
}
private fun printLineColumn(g: Graphics, col: Int, row: Int, s: String) {
g.drawString(s, (20 + column(col)).toFloat(), line(row).toFloat())
}
private fun line(i: Int): Int {
return i * 20
}
private fun column(i: Int): Int {
return 250 * (i - 1)
}
}

View File

@@ -1,92 +0,0 @@
package com.Torvald.Terrarum.UserInterface;
import com.Torvald.Terrarum.Terrarum;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.RoundedRectangle;
/**
* Created by minjaesong on 16-01-23.
*/
public class Bulletin implements UICanvas {
int width = 400;
int height;
int visibleTime = 5000;
int showupTimeConuter = 0;
boolean isShowing = false;
String[] message;
Color uiColour = new Color(0x90000000);
final int FRAME_SIZE = 5;
private RoundedRectangle uiBox = new RoundedRectangle(
width
, Terrarum.HEIGHT
, FRAME_SIZE
, 2
, RoundedRectangle.TOP_LEFT + RoundedRectangle.TOP_RIGHT
);
@Override
public void update(GameContainer gc, int delta_t) {
if (showupTimeConuter >= visibleTime) {
isShowing = false;
}
if (isShowing) {
showupTimeConuter += delta_t;
}
}
@Override
public void render(GameContainer gc, Graphics g) {
//if (isShowing) {
int lineHeight = Terrarum.gameFontWhite.getLineHeight();
g.setColor(uiColour);
g.fillRect(0
, getHeight() - message.length * lineHeight
- 10
, width
, getHeight()
);
for (int i = 0; i < message.length; i++) {
g.drawString(message[i]
, 5
, getHeight() - message.length * lineHeight
+ 5
+ (i * lineHeight)
);
}
//}
System.out.println("arst");
}
@Override
public void processInput(Input input) {
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return Terrarum.HEIGHT;
}
public void sendBulletin(String[] message) {
isShowing = true;
this.message = message;
}
}

View File

@@ -4,6 +4,7 @@ import com.Torvald.Terrarum.LangPack.Lang;
import com.Torvald.Terrarum.Terrarum;
import com.Torvald.Terrarum.ConsoleCommand.CommandInterpreter;
import com.Torvald.Terrarum.GameControl.Key;
import org.jetbrains.annotations.Nullable;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
@@ -144,8 +145,8 @@ public class ConsoleWindow implements UICanvas, UITypable {
}
public void reset() {
width = Terrarum.WIDTH;
height = 200;
setWidth(Terrarum.WIDTH);
setHeight(200);
messages = new String[MESSAGES_MAX];
messageDisplayPos = 0;
@@ -157,13 +158,25 @@ public class ConsoleWindow implements UICanvas, UITypable {
if (Terrarum.game.auth.b()) sendMessage(Lang.get("DEV_MESSAGE_CONSOLE_CODEX"));
}
@Nullable
@Override
public int getWidth() {
public Integer getWidth() {
return width;
}
@Override
public int getHeight() {
public void setWidth(@Nullable Integer integer) {
width = integer;
}
@Nullable
@Override
public Integer getHeight() {
return height;
}
@Override
public void setHeight(@Nullable Integer integer) {
height = integer;
}
}

View File

@@ -1,7 +1,7 @@
package com.Torvald.Terrarum.UserInterface;
import com.Torvald.ImageFont.GameFontBlack;
import com.Torvald.ImageFont.GameFontWhite;
import org.jetbrains.annotations.Nullable;
import org.newdawn.slick.*;
/**
@@ -12,7 +12,8 @@ public class Message implements UICanvas {
private Image segmentLeft, segmentRight, segmentBody;
private String[] messagesList;
private int messagesShowingIndex = 0;
// private int messagesShowingIndex = 0;
private static final int MESSAGES_DISPLAY = 2;
private int width;
private int height;
@@ -23,10 +24,11 @@ public class Message implements UICanvas {
public Message(int width, boolean isBlackVariant) throws SlickException {
if (!isBlackVariant) {
segmentLeft = new Image("./res/graphics/gui/message_twoline_white_left.png");
segmentRight = new Image("./res/graphics/gui/message_twoline_white_right.png");
segmentBody = new Image("./res/graphics/gui/message_twoline_white_body.png");
uiFont = new GameFontBlack();
//segmentLeft = new Image("./res/graphics/gui/message_twoline_white_left.png");
//segmentRight = new Image("./res/graphics/gui/message_twoline_white_right.png");
//segmentBody = new Image("./res/graphics/gui/message_twoline_white_body.png");
//uiFont = new GameFontBlack();
throw new SlickException("Black font not supported for now");
}
else {
segmentLeft = new Image("./res/graphics/gui/message_twoline_black_left.png");
@@ -60,14 +62,14 @@ public class Message implements UICanvas {
g.drawImage(segmentRight, width - segmentRight.getWidth(), 0);
g.setFont(uiFont);
g.setDrawMode(Graphics.MODE_NORMAL);
for (int i = messagesShowingIndex; i < messagesShowingIndex + 2; i++) {
//g.setDrawMode(Graphics.MODE_NORMAL);
for (int i = 0; i < Math.min(messagesList.length, MESSAGES_DISPLAY); i++) {
g.drawString(messagesList[i]
, messageWindowRadius + 4
, messageWindowRadius + (GLYPH_HEIGHT * (i - messagesShowingIndex))
, messageWindowRadius + (GLYPH_HEIGHT * i)
);
}
g.setDrawMode(Graphics.MODE_NORMAL);
//g.setDrawMode(Graphics.MODE_NORMAL);
}
@Override
@@ -75,13 +77,25 @@ public class Message implements UICanvas {
}
@Nullable
@Override
public int getWidth() {
public Integer getWidth() {
return width;
}
@Override
public int getHeight() {
public void setWidth(@Nullable Integer integer) {
width = integer;
}
@Nullable
@Override
public Integer getHeight() {
return height;
}
@Override
public void setHeight(@Nullable Integer integer) {
height = integer;
}
}

View File

@@ -0,0 +1,82 @@
package com.Torvald.Terrarum.UserInterface;
import com.Torvald.Terrarum.Terrarum;
import org.jetbrains.annotations.Nullable;
import org.newdawn.slick.*;
import org.newdawn.slick.geom.RoundedRectangle;
/**
* Created by minjaesong on 16-01-23.
*/
public class Notification implements UICanvas {
int width;
int height;
int visibleTime;
int showupTimeConuter = 0;
boolean isShowing = false;
String[] message;
Message msgUI;
public Notification() throws SlickException {
width = 400;
msgUI = new Message(width, true);
height = msgUI.getHeight();
visibleTime = Terrarum.getConfigInt("notificationshowuptime");
}
@Override
public void update(GameContainer gc, int delta_t) {
if (showupTimeConuter >= visibleTime) {
isShowing = false;
}
if (isShowing) {
showupTimeConuter += delta_t;
}
}
@Override
public void render(GameContainer gc, Graphics g) {
if (isShowing) {
msgUI.render(gc, g);
}
}
@Override
public void processInput(Input input) {
}
@Nullable
@Override
public Integer getWidth() {
return width;
}
@Override
public void setWidth(@Nullable Integer integer) {
width = integer;
}
@Nullable
@Override
public Integer getHeight() {
return height;
}
@Override
public void setHeight(@Nullable Integer integer) {
height = integer;
}
public void sendNotification(String[] message) {
isShowing = true;
this.message = message;
showupTimeConuter = 0;
msgUI.setMessage(this.message);
}
}

View File

@@ -0,0 +1,21 @@
package com.Torvald.Terrarum.UserInterface
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
import org.newdawn.slick.Input
/**
* Created by minjaesong on 16-03-14.
*/
interface UICanvas {
var width: Int?
var height: Int?
fun update(gc: GameContainer, delta_t: Int)
fun render(gc: GameContainer, g: Graphics)
fun processInput(input: Input)
}

View File

@@ -0,0 +1,21 @@
package com.Torvald.Terrarum.UserInterface
/**
* Created by minjaesong on 16-03-14.
*/
interface UIClickable {
fun mouseMoved(oldx: Int, oldy: Int, newx: Int, newy: Int)
fun mouseDragged(oldx: Int, oldy: Int, newx: Int, newy: Int)
fun mousePressed(button: Int, x: Int, y: Int)
fun mouseReleased(button: Int, x: Int, y: Int)
fun mouseWheelMoved(change: Int)
fun controllerButtonPressed(controller: Int, button: Int)
fun controllerButtonReleased(controller: Int, button: Int)
}

View File

@@ -0,0 +1,10 @@
package com.Torvald.Terrarum.UserInterface
/**
* Created by minjaesong on 16-03-14.
*/
interface UITypable {
fun keyPressed(key: Int, c: Char)
fun keyReleased(key: Int, c: Char)
}

View File

@@ -840,14 +840,14 @@ final public class FastMath {
}
public static float min(float... f) {
float[] sorted = f.clone();
Arrays.sort(f.clone());
return sorted[0];
float min = f[0];
for (int i = 1; i < f.length; i++) min = (f[i] < min) ? f[i] : min;
return min;
}
public static float max(float... f) {
float[] sorted = f.clone();
Arrays.sort(f.clone());
return sorted[sorted.length - 1];
float max = f[0];
for (int i = 1; i < f.length; i++) max = (f[i] > max) ? f[i] : max;
return max;
}
}

178
src/com/sudoplay/joise/Joise.java Executable file
View File

@@ -0,0 +1,178 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import com.sudoplay.joise.module.Module;
import com.sudoplay.joise.module.SeedableModule;
import com.sudoplay.util.Assert;
public class Joise {
private Module module;
private ModuleMap moduleMap;
private HashMap<String, ArrayList<SeedableModule>> seedMap = new HashMap<String, ArrayList<SeedableModule>>();
/**
* Creates a new instance of Joise with the supplied module chain.
* <p>
* This method duplicates the module chain by first converting the chain to a
* {@link ModuleMap}, then converting it back to a {@link Module} while
* mapping any seed names to the seedmap.
* <p>
* Changes made to the original module passed in will not be reflected in this
* instance of Joise.
*
* @param module
*/
public Joise(Module module) {
Assert.notNull(module);
moduleMap = module.getModuleMap();
this.module = fromModuleMap(moduleMap);
}
/**
* Creates a new instance of Joise from the supplied {@link ModuleMap}.
* <p>
* This method duplicates the module map by first converting the map to a
* {@link Module}, then converting it back to a module map. Seed names are
* mapped during the conversion from map to module.
* <p>
* Changes made to the original module map passed in will not be reflected in
* this instance of Joise.
*
* @param moduleMap
*/
public Joise(ModuleMap moduleMap) {
Assert.notNull(moduleMap);
this.module = fromModuleMap(moduleMap);
this.moduleMap = module.getModuleMap();
}
private Module fromModuleMap(ModuleMap map) {
try {
ModuleInstanceMap im = new ModuleInstanceMap();
Iterator<Entry<String, ModulePropertyMap>> it = map.mapIterator();
Module module = null;
while (it.hasNext()) {
Entry<String, ModulePropertyMap> e = it.next();
ModulePropertyMap props = e.getValue();
String moduleName = "com.sudoplay.joise.module." + props.get("module");
module = (Module) Class.forName(moduleName).newInstance();
module.buildFromPropertyMap(props, im);
if (module instanceof SeedableModule
&& ((SeedableModule) module).hasSeedName()) {
SeedableModule sm = (SeedableModule) module;
String seedName = sm.getSeedName();
ArrayList<SeedableModule> list = seedMap.get(seedName);
if (list == null) {
list = new ArrayList<SeedableModule>();
seedMap.put(seedName, list);
}
list.add(sm);
}
im.put(e.getKey(), module);
}
return module;
} catch (Exception e) {
throw new JoiseException(e);
}
}
/**
* Sets the seed of the module linked by seedName.
*
* @param seedName
* @param seed
* @throws IllegalStateException
* if the seed name is not found in the seed map
*/
public void setSeed(String seedName, long seed) {
ArrayList<SeedableModule> list = seedMap.get(seedName);
if (list == null || list.isEmpty()) {
throw new IllegalStateException("Seed name not found: " + seedName);
}
for (SeedableModule sm : list) {
sm.setSeed(seed);
}
}
public boolean hasSeed(String seedName) {
return seedMap.get(seedName) != null;
}
/**
* @return the stored module map for this Joise
*/
public ModuleMap getModuleMap() {
return moduleMap;
}
public double get(double x, double y) {
return module.get(x, y);
}
public double get(double x, double y, double z) {
return module.get(x, y, z);
}
public double get(double x, double y, double z, double w) {
return module.get(x, y, z, w);
}
public double get(double x, double y, double z, double w, double u, double v) {
return module.get(x, y, z, w, u, v);
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise;
@SuppressWarnings("serial")
public class JoiseException extends RuntimeException {
public JoiseException(String msg) {
super(msg);
}
public JoiseException(Exception e) {
super(e);
}
public JoiseException(String msg, Exception e) {
super(msg, e);
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import com.sudoplay.joise.module.Module;
@SuppressWarnings("serial")
public class ModuleInstanceMap extends HashMap<String, Module> {
@Override
public Module put(String id, Module module) {
if (id == null) {
throw new NullPointerException("null id");
}
if (module == null) {
throw new NullPointerException("null module, id=" + id);
}
return super.put(id, module);
}
@Override
public Module get(Object key) {
Module module = super.get(key);
if (module == null) {
throw new NullPointerException("null module, id=" + key);
}
return module;
}
public boolean contains(String id) {
return super.get(id) != null;
}
public Iterator<Entry<String, Module>> iterator() {
return super.entrySet().iterator();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
Iterator<Entry<String, Module>> it = iterator();
while (it.hasNext()) {
Entry<String, Module> e = it.next();
sb.append("[");
sb.append(e.getKey());
sb.append("|");
sb.append(e.getValue());
sb.append("]");
}
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
@SuppressWarnings("serial")
public class ModuleMap extends LinkedHashMap<String, ModulePropertyMap> {
@Override
public ModulePropertyMap put(String module, ModulePropertyMap propertyMap) {
if (propertyMap == null) {
throw new NullPointerException("property map for module [" + module
+ "] null");
}
return super.put(module, propertyMap);
}
@Override
public ModulePropertyMap get(Object key) {
ModulePropertyMap props = super.get(key);
if (props == null) {
throw new NullPointerException("property map [" + key + "] null");
}
return super.get(key);
}
public boolean contains(String id) {
return super.get(id) != null;
}
public Iterator<Entry<String, ModulePropertyMap>> mapIterator() {
return super.entrySet().iterator();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
Iterator<Entry<String, ModulePropertyMap>> it = mapIterator();
while (it.hasNext()) {
Entry<String, ModulePropertyMap> e = it.next();
sb.append("[");
sb.append(e.getKey());
sb.append("|");
sb.append(e.getValue());
sb.append("]");
}
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,154 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import com.sudoplay.joise.module.Module;
@SuppressWarnings("serial")
public class ModulePropertyMap extends LinkedHashMap<String, Object> {
public ModulePropertyMap() {
// serialization
}
public ModulePropertyMap(Module module) {
setModule(module);
}
public void setModule(Module module) {
super.put("module", module.getClass().getSimpleName());
}
@Override
public Object put(String key, Object value) {
if (key == null) {
throw new NullPointerException();
}
if (value == null) {
return super.put(key, null);
} else {
return super.put(key, value.toString());
}
}
@Override
public Object get(Object key) {
if (key == null) {
throw new NullPointerException();
}
Object value = super.get(key);
return value;
}
public String getAsString(String key) {
return get(key).toString();
}
public long getAsLong(String key) {
try {
return Long.parseLong(getAsString(key));
} catch (NumberFormatException e) {
throw new JoiseException("Expecting property [" + key + ", "
+ getAsString(key) + "] to be a long");
}
}
public double getAsDouble(String key) {
try {
return Double.parseDouble(getAsString(key));
} catch (NumberFormatException e) {
throw new JoiseException("Expecting property [" + key + ", "
+ getAsString(key) + "] to be a double");
}
}
public boolean getAsBoolean(String key) {
String candidate = getAsString(key).toLowerCase();
if ("true".equals(candidate) || "false".equals(candidate)) {
return Boolean.parseBoolean(getAsString(key));
} else {
throw new JoiseException("Expecting property [" + key + ", "
+ getAsString(key) + "] to be a boolean");
}
}
public boolean isModuleID(String key) {
return getAsString(key).startsWith("func_");
}
public boolean contains(String key) {
return super.get(key) != null;
}
public Iterator<Entry<String, Object>> iterator() {
return super.entrySet().iterator();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Iterator<Entry<String, Object>> it = iterator();
while (it.hasNext()) {
Entry<String, Object> e = it.next();
sb.append("[");
sb.append(e.getKey());
sb.append("|");
sb.append(e.getValue());
sb.append("]");
}
return sb.toString();
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
public abstract class BasePRNG {
public abstract int get();
public abstract void setSeed(long seed);
public void setSeedTime() {
setSeed(System.currentTimeMillis());
}
public int getTarget(int t) {
double v = get01();
return (int) (v * (double) t);
}
public double get01() {
return ((double) get() / (double) 4294967295L) + 0.5;
}
public int getRange(int low, int high) {
if (high < low) {
int temp = low;
low = high;
high = temp;
}
double range = (double) ((high - low) + 1);
double val = (double) low + get01() * range;
return (int) val;
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
/**
* Complimentary multiply with carry.
*/
public class CMWC4096 extends BasePRNG {
protected int c;
protected int[] Q = new int[4096];
protected LCG lcg = new LCG();
protected int i;
public CMWC4096() {
setSeed(10000);
}
@Override
public int get() {
long t;
long a = 18782L;
long b = 4294967295L;
int r = (int) (b - 1);
i = (i + 1) & 4095;
t = a * Q[i] + c;
c = (int) (t >> 32);
t = (t & b) + c;
if (t > r) {
c++;
t = t - b;
}
return Q[i] = (int) (r - t);
}
@Override
public void setSeed(long seed) {
lcg.setSeed(seed);
for (int i = 0; i < 4096; i++) {
Q[i] = lcg.get();
}
c = lcg.getTarget(18781);
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
public class KISS extends BasePRNG {
protected LCG lcg = new LCG();
protected int z, w, jsr, jcong;
public KISS() {
setSeed(10000);
}
@Override
public int get() {
z = 36969 * (z & 65535) + (z >> 16);
w = 18000 * (w & 65535) + (w >> 16);
int mwc = (z << 16) + w;
jcong = 69069 * jcong + 1234567;
jsr ^= (jsr << 17);
jsr ^= (jsr >> 13);
jsr ^= (jsr << 5);
return ((mwc ^ jcong) + jsr);
}
@Override
public void setSeed(long seed) {
lcg.setSeed(seed);
z = lcg.get();
w = lcg.get();
jsr = lcg.get();
jcong = lcg.get();
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
/**
* Linear congruential generator.
*/
public class LCG extends BasePRNG {
protected long state;
public LCG() {
setSeed(10000);
}
@Override
public int get() {
return (int) (state = (25214903917L * state + 11) % 281474976710656L);
}
@Override
public void setSeed(long seed) {
state = (int) seed;
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
/**
* Multiply with carry.
*/
public class MWC extends BasePRNG {
protected LCG lcg = new LCG();
protected long x;
protected long a = 0xffffda61L;
public MWC() {
setSeed(10000);
}
@Override
public int get() {
return (int) (x = (a * (x & 0xffffffffL)) + (x >>> 32));
}
@Override
public void setSeed(long seed) {
lcg.setSeed(seed);
x = lcg.get() & 0xffffffffL;
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
/**
* Multiply with carry.
*/
public class MWC256 extends BasePRNG {
protected int[] Q = new int[256];
protected int c;
protected LCG lcg = new LCG();
protected byte b = (byte) 255;
public MWC256() {
setSeed(10000);
}
@Override
public int get() {
long t;
long a = 809430660L;
t = a * Q[++b & 0xFF] + c;
c = (int) (t >> 32);
return Q[b & 0xFF] = (int) t;
}
@Override
public void setSeed(long seed) {
lcg.setSeed(seed);
for (int i = 0; i < 256; i++) {
Q[i] = lcg.get();
}
c = lcg.getTarget(809430660);
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.generator;
public class XORShift extends BasePRNG {
protected int x, y, z, w, v;
protected LCG lcg = new LCG();
public XORShift() {
setSeed(10000);
}
@Override
public int get() {
int t;
t = (x ^ (x >> 7));
x = y;
y = z;
z = w;
w = v;
v = (v ^ (v << 6)) ^ (t ^ (t << 13));
return (y + y + 1) * v;
}
@Override
public void setSeed(long seed) {
lcg.setSeed(seed);
x = lcg.get();
y = lcg.get();
z = lcg.get();
w = lcg.get();
v = lcg.get();
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public class Array2Double {
public static final byte X = 0;
public static final byte Y = 1;
private int[] size = new int[2];
private double[] data;
@SuppressWarnings("unused")
private Array2Double() {}
public Array2Double(int x, int y) {
this(x, y, new double[x * y]);
}
public Array2Double(int x, int y, double[] data) {
size[X] = x;
size[Y] = y;
this.data = data;
}
public void set(int x, int y, double v) {
data[x + size[X] * y] = v;
}
public double get(int x, int y) {
return data[x + size[X] * y];
}
public double[] getData() {
return data;
}
public int[] getSize() {
return size;
}
public int getWidth() {
return size[X];
}
public int getHeight() {
return size[Y];
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public class Array2DoubleWriter implements Mapping2DWriter {
private Array2Double data;
public Array2DoubleWriter(int x, int y) {
this(new Array2Double(x, y));
}
public Array2DoubleWriter(Array2Double data) {
this.data = data;
}
public Array2Double getData() {
return data;
}
@Override
public void write(int x, int y, double value) {
data.set(x, y, value);
}
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public class Array3Double {
public static final byte X = 0;
public static final byte Y = 1;
public static final byte Z = 2;
public static final byte XY = 3;
private int[] size = new int[4];
private double[] data;
@SuppressWarnings("unused")
private Array3Double() {}
public Array3Double(int x, int y, int z) {
size[X] = x;
size[Y] = y;
size[Z] = z;
size[XY] = x * y;
data = new double[x * y * z];
}
public void set(int x, int y, int z, double v) {
data[x + (size[X] * y) + (size[XY] * z)] = v;
}
public double get(int x, int y, int z) {
return data[x + (size[X] * y) + (size[XY] * z)];
}
public double[] getData() {
return data;
}
public int[] getSize() {
return size;
}
public int getWidth() {
return size[X];
}
public int getHeight() {
return size[Y];
}
public int getDepth() {
return size[Z];
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public class Array3DoubleWriter implements Mapping3DWriter {
private Array3Double data;
public Array3DoubleWriter(int x, int y, int z) {
this(new Array3Double(x, y, z));
}
public Array3DoubleWriter(Array3Double data) {
this.data = data;
}
public Array3Double getData() {
return data;
}
@Override
public void write(int x, int y, int z, double value) {
data.set(x, y, z, value);
}
}

View File

@@ -0,0 +1,753 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
import com.sudoplay.joise.module.Module;
public final class Mapping {
private static final double TWO_PI = Math.PI * 2.0;
private Mapping() {
// do not instantiate
}
public static void map2D(MappingMode mode, int width, int height, Module m,
MappingRange range, Mapping2DWriter writer,
MappingUpdateListener listener, double z) {
if (writer == null) {
writer = Mapping2DWriter.NULL_WRITER;
}
if (listener == null) {
listener = MappingUpdateListener.NULL_LISTENER;
}
double p, q;
double nx, ny, nz, nw, nu, nv;
double r;
double zval;
double dx, dy, dz;
double dx_div_2pi;
double dy_div_2pi;
double dz_div_2pi;
double iw = 1.0 / (double) width;
double ih = 1.0 / (double) height;
double total = width * height;
double current = 0;
switch (mode) {
case NORMAL:
dx = range.map1.x - range.map0.x;
dy = range.map1.y - range.map0.y;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
nx = range.map0.x + p * dx;
ny = range.map0.y + q * dy;
nz = z;
writer.write(x, y, m.get(nx, ny, nz));
listener.update(++current, total);
}
}
return;
case SEAMLESS_X:
dx = range.loop1.x - range.loop0.x;
dy = range.map1.y - range.map0.y;
dx_div_2pi = dx / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
p = p * (range.map1.x - range.map0.x) / dx;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.map0.y + q * dy;
nw = z;
writer.write(x, y, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
return;
case SEAMLESS_Y:
dx = range.map1.x - range.map0.x;
dy = range.loop1.y - range.loop0.y;
dy_div_2pi = dy / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.map0.x + p * dx;
ny = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nz = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nw = z;
writer.write(x, y, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
return;
case SEAMLESS_Z:
dx = range.map1.x - range.map0.x;
dy = range.map1.y - range.map0.y;
dz = range.loop1.z - range.loop0.z;
r = (z - range.map0.z) / (range.map1.z - range.map0.z);
zval = r * (range.map1.z - range.map0.z) / dz;
dz_div_2pi = dz / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
nx = range.map0.x + p * dx;
ny = range.map0.y + p * dx;
nz = range.loop0.z + Math.cos(zval * TWO_PI) * dz_div_2pi;
nw = range.loop0.z + Math.sin(zval * TWO_PI) * dz_div_2pi;
writer.write(x, y, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
return;
case SEAMLESS_XY:
dx = range.loop1.x - range.loop0.x;
dy = range.loop1.y - range.loop0.y;
dx_div_2pi = dx / TWO_PI;
dy_div_2pi = dy / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
p = p * (range.map1.x - range.map0.x) / dx;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nu = z;
nv = 0;
writer.write(x, y, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
return;
case SEAMLESS_XZ:
dx = range.loop1.x - range.loop0.x;
dy = range.map1.y - range.map0.y;
dz = range.loop1.z - range.loop0.z;
dx_div_2pi = dx / TWO_PI;
dz_div_2pi = dz / TWO_PI;
r = (z - range.map0.z) / (range.map1.z - range.map0.z);
zval = r * (range.map1.z - range.map0.z) / dz;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
p = p * (range.map1.x - range.map0.x) / dz;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.map0.y + q * dy;
nw = range.loop0.z + Math.cos(zval * TWO_PI) * dz_div_2pi;
nu = range.loop0.z + Math.sin(zval * TWO_PI) * dz_div_2pi;
nv = 0;
writer.write(x, y, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
return;
case SEAMLESS_YZ:
dx = range.map1.x - range.map0.x;
dy = range.loop1.y - range.loop0.y;
dz = range.loop1.z - range.loop0.z;
dy_div_2pi = dy / TWO_PI;
dz_div_2pi = dz / TWO_PI;
r = (z - range.map0.z) / (range.map1.z - range.map0.z);
zval = r * (range.map1.z - range.map0.z) / dz;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.map0.x + p * dx;
ny = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nz = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.z + Math.cos(zval * TWO_PI) * dz_div_2pi;
nu = range.loop0.z + Math.sin(zval * TWO_PI) * dz_div_2pi;
nv = 0;
writer.write(x, y, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
return;
case SEAMLESS_XYZ:
dx = range.loop1.x - range.loop0.x;
dy = range.loop1.y - range.loop0.y;
dz = range.loop1.z - range.loop0.z;
dx_div_2pi = dx / TWO_PI;
dy_div_2pi = dy / TWO_PI;
dz_div_2pi = dz / TWO_PI;
r = (z - range.map0.z) / (range.map1.z - range.map0.z);
zval = r * (range.map1.z - range.map0.z) / dz;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
p = p * (range.map1.x - range.map0.x) / dx;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nu = range.loop0.z + Math.cos(zval * TWO_PI) * dz_div_2pi;
nv = range.loop0.z + Math.sin(zval * TWO_PI) * dz_div_2pi;
writer.write(x, y, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
return;
default:
throw new AssertionError();
}
}
public static void map2DNoZ(MappingMode mode, int width, int height,
Module m, MappingRange range, Mapping2DWriter writer,
MappingUpdateListener listener) {
if (writer == null) {
writer = Mapping2DWriter.NULL_WRITER;
}
if (listener == null) {
listener = MappingUpdateListener.NULL_LISTENER;
}
double p, q;
double nx, ny, nz, nw;
double dx, dy;
double dx_div_2pi;
double dy_div_2pi;
double iw = 1.0 / (double) width;
double ih = 1.0 / (double) height;
double total = width * height;
double current = 0;
switch (mode) {
case NORMAL:
dx = range.map1.x - range.map0.x;
dy = range.map1.y - range.map0.y;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
nx = range.map0.x + p * dx;
ny = range.map0.y + q * dy;
writer.write(x, y, m.get(nx, ny));
listener.update(++current, total);
}
}
return;
case SEAMLESS_X:
dx = range.loop1.x - range.loop0.x;
dy = range.map1.y - range.map0.y;
dx_div_2pi = dx / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
p = p * (range.map1.x - range.map0.x) / dx;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.map0.y + q * dy;
writer.write(x, y, m.get(nx, ny, nz));
listener.update(++current, total);
}
}
return;
case SEAMLESS_Y:
dx = range.map1.x - range.map0.x;
dy = range.loop1.y - range.loop0.y;
dy_div_2pi = dy / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.map0.x + p * dx;
ny = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nz = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
writer.write(x, y, m.get(nx, ny, nz));
listener.update(++current, total);
}
}
return;
case SEAMLESS_XY:
dx = range.loop1.x - range.loop0.x;
dy = range.loop1.y - range.loop0.y;
dx_div_2pi = dx / TWO_PI;
dy_div_2pi = dy / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p = (double) x * iw;
q = (double) y * ih;
p = p * (range.map1.x - range.map0.x) / dx;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
writer.write(x, y, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
return;
case SEAMLESS_Z:
case SEAMLESS_XZ:
case SEAMLESS_YZ:
case SEAMLESS_XYZ:
throw new UnsupportedOperationException(mode.toString());
default:
throw new AssertionError();
}
}
public static void map3D(MappingMode mode, int width, int height, int depth,
Module m, MappingRange range, Mapping3DWriter writer,
MappingUpdateListener listener) {
if (writer == null) {
writer = Mapping3DWriter.NULL_WRITER;
}
if (listener == null) {
listener = MappingUpdateListener.NULL_LISTENER;
}
double p, q, r;
double nx, ny, nz, nw, nu, nv;
double dx, dy, dz;
double dx_div_2pi;
double dy_div_2pi;
double dz_div_2pi;
double iw = 1.0 / (double) width;
double ih = 1.0 / (double) height;
double id = 1.0 / (double) depth;
double total = width * height * depth;
double current = 0;
switch (mode) {
case NORMAL:
dx = range.map1.x - range.map0.x;
dy = range.map1.y - range.map0.y;
dz = range.map1.z - range.map0.z;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
nx = range.map0.x + p * dx;
ny = range.map0.y + q * dy;
nz = range.map0.z + r * dz;
writer.write(x, y, z, m.get(nx, ny, nz));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_X:
dx = range.loop1.x - range.loop0.x;
dy = range.map1.y - range.map0.y;
dz = range.map1.z - range.map0.z;
dx_div_2pi = dx / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
p = p * (range.map1.x - range.map0.x) / dx;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.map0.y + q * dy;
nw = range.map0.z + r * dz;
writer.write(x, y, z, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_Y:
dx = range.map1.x - range.map0.x;
dy = range.loop1.y - range.loop0.y;
dz = range.map1.z - range.map0.z;
dy_div_2pi = dy / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.map0.x + p * dx;
ny = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nz = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nw = range.map0.z + r * dz;
writer.write(x, y, z, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_Z:
dx = range.map1.x - range.map0.x;
dy = range.map1.y - range.map0.y;
dz = range.loop1.z - range.loop0.z;
dz_div_2pi = dz / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
r = r * (range.map1.z - range.map0.z) / dz;
nx = range.map0.x + p * dx;
ny = range.map0.y + q * dy;
nz = range.loop0.z + Math.cos(r * TWO_PI) * dz_div_2pi;
nw = range.loop0.z + Math.sin(r * TWO_PI) * dz_div_2pi;
writer.write(x, y, z, m.get(nx, ny, nz, nw));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_XY:
dx = range.loop1.x - range.loop0.x;
dy = range.loop1.y - range.loop0.y;
dz = range.map1.z - range.map0.z;
dx_div_2pi = dx / TWO_PI;
dy_div_2pi = dy / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
p = p * (range.map1.x - range.map0.x) / dx;
q = q * (range.map1.y - range.map0.y) / dy;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nu = range.map0.z + r * dz;
nv = 0;
writer.write(x, y, z, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_XZ:
dx = range.loop1.x - range.loop0.x;
dy = range.map1.y - range.map0.y;
dz = range.loop1.z - range.loop0.z;
dx_div_2pi = dx / TWO_PI;
dz_div_2pi = dz / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
p = p * (range.map1.x - range.map0.x) / dx;
r = r * (range.map1.z - range.map0.z) / dz;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.map0.y + q * dy;
nw = range.loop0.z + Math.cos(r * TWO_PI) * dz_div_2pi;
nu = range.loop0.z + Math.sin(r * TWO_PI) * dz_div_2pi;
nv = 0;
writer.write(x, y, z, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_YZ:
dx = range.map1.x - range.map0.x;
dy = range.loop1.y - range.loop0.y;
dz = range.loop1.z - range.loop0.z;
dy_div_2pi = dy / TWO_PI;
dz_div_2pi = dz / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
q = q * (range.map1.y - range.map0.y) / dy;
r = r * (range.map1.z - range.map0.z) / dz;
nx = range.map0.x + p * dx;
ny = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nz = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.z + Math.cos(r * TWO_PI) * dz_div_2pi;
nu = range.loop0.z + Math.sin(r * TWO_PI) * dz_div_2pi;
nv = 0;
writer.write(x, y, z, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
}
return;
case SEAMLESS_XYZ:
dx = range.loop1.x - range.loop0.x;
dy = range.loop1.y - range.loop0.y;
dz = range.loop1.z - range.loop0.z;
dx_div_2pi = dx / TWO_PI;
dy_div_2pi = dy / TWO_PI;
dz_div_2pi = dz / TWO_PI;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < depth; z++) {
p = (double) x * iw;
q = (double) y * ih;
r = (double) z * id;
p = p * (range.map1.x - range.map0.x) / dx;
q = q * (range.map1.y - range.map0.y) / dy;
r = r * (range.map1.z - range.map0.z) / dz;
nx = range.loop0.x + Math.cos(p * TWO_PI) * dx_div_2pi;
ny = range.loop0.x + Math.sin(p * TWO_PI) * dx_div_2pi;
nz = range.loop0.y + Math.cos(q * TWO_PI) * dy_div_2pi;
nw = range.loop0.y + Math.sin(q * TWO_PI) * dy_div_2pi;
nu = range.loop0.z + Math.cos(r * TWO_PI) * dz_div_2pi;
nv = range.loop0.z + Math.sin(r * TWO_PI) * dz_div_2pi;
writer.write(x, y, z, m.get(nx, ny, nz, nw, nu, nv));
listener.update(++current, total);
}
}
}
return;
default:
throw new AssertionError();
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public interface Mapping2DWriter {
public void write(int x, int y, double value);
public static final Mapping2DWriter NULL_WRITER = new Mapping2DWriter() {
@Override
public void write(int x, int y, double value) {
// do nothing
}
};
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public interface Mapping3DWriter {
public void write(int x, int y, int z, double value);
public static final Mapping3DWriter NULL_WRITER = new Mapping3DWriter() {
@Override
public void write(int x, int y, int z, double value) {
// do nothing
}
};
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public enum MappingMode {
NORMAL, SEAMLESS_X, SEAMLESS_Y, SEAMLESS_Z, SEAMLESS_XY, SEAMLESS_XZ, SEAMLESS_YZ, SEAMLESS_XYZ
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
import com.sudoplay.joise.noise.Util.Vector3d;
public class MappingRange {
public Vector3d map0 = new Vector3d(-1, -1, -1);
public Vector3d map1 = new Vector3d(1, 1, 1);
public Vector3d loop0 = new Vector3d(-1, -1, -1);
public Vector3d loop1 = new Vector3d(1, 1, 1);
public static final MappingRange DEFAULT = new MappingRange();
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.mapping;
public interface MappingUpdateListener {
public void update(double current, double total);
public static final MappingUpdateListener NULL_LISTENER = new MappingUpdateListener() {
@Override
public void update(double current, double total) {
// do nothing
}
};
}

View File

@@ -0,0 +1,371 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;
import com.sudoplay.joise.JoiseException;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public abstract class Module {
public static final long DEFAULT_SEED = 10000;
public static final int MAX_SOURCES = 10;
protected double spacing = 0.0001;
public abstract double get(double x, double y);
public abstract double get(double x, double y, double z);
public abstract double get(double x, double y, double z, double w);
public abstract double get(double x, double y, double z, double w, double u,
double v);
protected static AtomicInteger nextId = new AtomicInteger();
private String id = setId();
protected String setId() {
return "func_" + nextId.incrementAndGet();
}
public String getId() {
return id;
}
public ModuleMap getModuleMap() {
ModuleMap map = new ModuleMap();
_writeToMap(map);
return map;
}
public void writeToMap(ModuleMap map) {
if (map.contains(id)) {
return;
}
_writeToMap(map);
}
protected abstract void _writeToMap(ModuleMap map);
public abstract Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map);
public void setDerivativeSpacing(double spacing) {
this.spacing = spacing;
}
public double getDX(double x, double y) {
return (get(x - spacing, y) - get(x + spacing, y)) / spacing;
}
public double getDY(double x, double y) {
return (get(x, y - spacing) - get(x, y + spacing)) / spacing;
}
public double getDX(double x, double y, double z) {
return (get(x - spacing, y, z) - get(x + spacing, y, z)) / spacing;
}
public double getDY(double x, double y, double z) {
return (get(x, y - spacing, z) - get(x, y + spacing, z)) / spacing;
}
public double getDZ(double x, double y, double z) {
return (get(x, y, z - spacing) - get(x, y, z + spacing)) / spacing;
}
public double getDX(double x, double y, double z, double w) {
return (get(x - spacing, y, z, w) - get(x + spacing, y, z, w)) / spacing;
}
public double getDY(double x, double y, double z, double w) {
return (get(x, y - spacing, z, w) - get(x, y + spacing, z, w)) / spacing;
}
public double getDZ(double x, double y, double z, double w) {
return (get(x, y, z - spacing, w) - get(x, y, z + spacing, w)) / spacing;
}
public double getDW(double x, double y, double z, double w) {
return (get(x, y, z, w - spacing) - get(x, y, z, w + spacing)) / spacing;
}
public double getDX(double x, double y, double z, double w, double u, double v) {
return (get(x - spacing, y, z, w, u, v) - get(x + spacing, y, z, w, u, v))
/ spacing;
}
public double getDY(double x, double y, double z, double w, double u, double v) {
return (get(x, y - spacing, z, w, u, v) - get(x, y + spacing, z, w, u, v))
/ spacing;
}
public double getDZ(double x, double y, double z, double w, double u, double v) {
return (get(x, y, z - spacing, w, u, v) - get(x, y, z + spacing, w, u, v))
/ spacing;
}
public double getDW(double x, double y, double z, double w, double u, double v) {
return (get(x, y, z, w - spacing, u, v) - get(x, y, z, w + spacing, u, v))
/ spacing;
}
public double getDU(double x, double y, double z, double w, double u, double v) {
return (get(x, y, z, w, u - spacing, v) - get(x, y, z, w, u + spacing, v))
/ spacing;
}
public double getDV(double x, double y, double z, double w, double u, double v) {
return (get(x, y, z, w, u, v - spacing) - get(x, y, z, w, u, v + spacing))
/ spacing;
}
protected void assertMaxSources(int index) {
if (index < 0 || index >= MAX_SOURCES) {
throw new IllegalArgumentException("expecting index < " + MAX_SOURCES
+ " but was " + index);
}
}
/**
* Read a scalar property from the provided property map and set the property
* in this module using reflection to call the supplied method name with the
* retrieved property passed as an argument. If the scalar is a module name,
* the module is retrieved from the provided {@link ModuleInstanceMap} and set
* using the reflected method provided.
*
* @param name
* @param methodName
* @param props
* @param map
*
* @throws JoiseException
* if there is an error with the retrieval or setting of the
* property
*/
protected void readScalar(String name, String methodName,
ModulePropertyMap props, ModuleInstanceMap map) {
try {
if (props.isModuleID(name)) {
Method method = getClass().getMethod(methodName, Module.class);
method.invoke(this, new Object[] { map.get(props.get(name)) });
} else {
Method method = getClass().getMethod(methodName, double.class);
method.invoke(this, new Object[] { props.getAsDouble(name) });
}
} catch (Exception e) {
throw new JoiseException(e);
}
}
/**
* Write a scalar property to the provided property map. If the scalar is a
* module, {@link #_writeToMap(ModuleMap)} is called on the scalar's module.
*
* @param key
* @param scalar
* @param props
* @param map
*/
protected void writeScalar(String key, ScalarParameter scalar,
ModulePropertyMap props, ModuleMap map) {
props.put(key, scalar);
if (scalar != null && scalar.isModule()) {
scalar.getModule()._writeToMap(map);
}
}
/**
* Read an enum property from the provided property map and set the property
* in this module using reflection to call the supplied method name with the
* retrieved property passed as an argument.
*
* @param name
* @param methodName
* @param c
* @param props
*/
protected <T extends Enum<T>> void readEnum(String name, String methodName,
Class<T> c, ModulePropertyMap props) {
try {
Method method = getClass().getMethod(methodName, c);
T _enum = Enum.valueOf(c, props.get(name).toString().toUpperCase());
method.invoke(this, new Object[] { _enum });
} catch (Exception e) {
throw new JoiseException(e);
}
}
/**
* Write an enum property to the provided property map. The enum is converted
* to lower-case.
*
* @param key
* @param _enum
* @param props
*/
protected void writeEnum(String key, Enum<?> _enum, ModulePropertyMap props) {
props.put(key, _enum.toString().toLowerCase());
}
/**
* Read a long property from the provided property map and set the property in
* this module using reflection to call the supplied method name with the
* retrieved property passed as an argument.
*
* @param key
* @param methodName
* @param props
*/
protected void readLong(String key, String methodName, ModulePropertyMap props) {
try {
Method method = getClass().getMethod(methodName, long.class);
method.invoke(this, new Object[] { props.getAsLong(key) });
} catch (Exception e) {
throw new JoiseException(e);
}
}
/**
* Write a long property to the provided property map.
*
* @param key
* @param value
* @param props
*/
protected void writeLong(String key, long value, ModulePropertyMap props) {
props.put(key, value);
}
/**
* Read a double property from the provided property map and set the property
* in this module using reflection to call the supplied method name with the
* retrieved property passed as an argument.
*
* @param key
* @param methodName
* @param props
*/
protected void readDouble(String key, String methodName,
ModulePropertyMap props) {
try {
Method method = getClass().getMethod(methodName, double.class);
method.invoke(this, new Object[] { props.getAsDouble(key) });
} catch (Exception e) {
throw new JoiseException(e);
}
}
/**
* Write a double property to the provided property map.
*
* @param key
* @param value
* @param props
*/
protected void writeDouble(String key, double value, ModulePropertyMap props) {
props.put(key, value);
}
/**
* Read a boolean property from the provided property map and set the property
* in this module using reflection to call the supplied method name with the
* retrieved property passed as an argument.
*
* @param key
* @param methodName
* @param props
*/
protected void readBoolean(String key, String methodName,
ModulePropertyMap props) {
try {
Method method = getClass().getMethod(methodName, boolean.class);
method.invoke(this, new Object[] { props.getAsBoolean(key) });
} catch (Exception e) {
throw new JoiseException(e);
}
}
/**
* Write a boolean property to the provided property map.
*
* @param key
* @param value
* @param props
*/
protected void writeBoolean(String key, boolean value, ModulePropertyMap props) {
props.put(key, String.valueOf(value));
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleAbs extends SourcedModule {
@Override
public double get(double x, double y) {
return Math.abs(source.get(x, y));
}
@Override
public double get(double x, double y, double z) {
return Math.abs(source.get(x, y, z));
}
@Override
public double get(double x, double y, double z, double w) {
return Math.abs(source.get(x, y, z, w));
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
return Math.abs(source.get(x, y, z, w, u, v));
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readSource(props, map);
return this;
}
}

View File

@@ -0,0 +1,305 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import static com.sudoplay.joise.noise.Util.clamp;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
import com.sudoplay.joise.generator.LCG;
import com.sudoplay.util.Checked;
public class ModuleAutoCorrect extends SourcedModule {
public static final double DEFAULT_LOW = 0.0;
public static final double DEFAULT_HIGH = 1.0;
public static final int DEFAULT_SAMPLES = 100;
public static final double DEFAULT_SAMPLE_SCALE = 1.0;
protected double low;
protected double high;
protected double sampleScale = DEFAULT_SAMPLE_SCALE;
protected double scale2, offset2;
protected double scale3, offset3;
protected double scale4, offset4;
protected double scale6, offset6;
protected boolean locked;
protected int samples = DEFAULT_SAMPLES;
public ModuleAutoCorrect() {
this(DEFAULT_LOW, DEFAULT_HIGH);
}
public ModuleAutoCorrect(double low, double high) {
this.low = low;
this.high = high;
}
public void setRange(double low, double high) {
this.low = low;
this.high = high;
}
public void setLow(double low) {
this.low = low;
}
public void setHigh(double high) {
this.high = high;
}
public void setSamples(long s) {
samples = Checked.safeLongToInt(s);
}
public void setSampleScale(double s) {
sampleScale = s;
}
public void setLocked(boolean lock) {
locked = lock;
}
@Override
public void setSource(double source) {
super.setSource(source);
}
@Override
public void setSource(Module source) {
super.setSource(source);
}
public void calculate() {
if (!source.isModule() || locked) return;
double mn, mx;
LCG lcg = new LCG();
// Calculate 2D
mn = 10000.0;
mx = -10000.0;
for (int c = 0; c < samples; c++) {
double nx = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double ny = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double v = source.get(nx, ny);
if (v < mn) mn = v;
if (v > mx) mx = v;
}
scale2 = (high - low) / (mx - mn);
offset2 = low - mn * scale2;
// Calculate 3D
mn = 10000.0;
mx = -10000.0;
for (int c = 0; c < samples; c++) {
double nx = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double ny = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nz = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double v = source.get(nx, ny, nz);
if (v < mn) mn = v;
if (v > mx) mx = v;
}
scale3 = (high - low) / (mx - mn);
offset3 = low - mn * scale3;
// Calculate 4D
mn = 10000.0;
mx = -10000.0;
for (int c = 0; c < samples; c++) {
double nx = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double ny = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nz = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nw = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double v = source.get(nx, ny, nz, nw);
if (v < mn) mn = v;
if (v > mx) mx = v;
}
scale4 = (high - low) / (mx - mn);
offset4 = low - mn * scale4;
// Calculate 6D
mn = 10000.0;
mx = -10000.0;
for (int c = 0; c < samples; c++) {
double nx = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double ny = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nz = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nw = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nu = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double nv = (lcg.get01() * 4.0 - 2.0) * sampleScale;
double v = source.get(nx, ny, nz, nw, nu, nv);
if (v < mn) mn = v;
if (v > mx) mx = v;
}
scale6 = (high - low) / (mx - mn);
offset6 = low - mn * scale6;
}
@Override
public double get(double x, double y) {
double v = source.get(x, y);
return clamp(v * scale2 + offset2, low, high);
}
@Override
public double get(double x, double y, double z) {
double v = source.get(x, y, z);
return clamp(v * scale3 + offset3, low, high);
}
@Override
public double get(double x, double y, double z, double w) {
double v = source.get(x, y, z, w);
return clamp(v * scale4 + offset4, low, high);
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
double val = source.get(x, y, z, w, u, v);
return clamp(val * scale6 + offset6, low, high);
}
public double getOffset2D() {
return offset2;
}
public double getOffset3D() {
return offset3;
}
public double getOffset4D() {
return offset4;
}
public double getOffset6D() {
return offset6;
}
public double getScale2D() {
return scale2;
}
public double getScale3D() {
return scale3;
}
public double getScale4D() {
return scale4;
}
public double getScale6D() {
return scale6;
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeDouble("low", low, props);
writeDouble("high", high, props);
writeLong("samples", samples, props);
writeDouble("sampleScale", sampleScale, props);
writeBoolean("locked", locked, props);
if (locked) {
writeDouble("scale2", scale2, props);
writeDouble("offset2", offset2, props);
writeDouble("scale3", scale3, props);
writeDouble("offset3", offset3, props);
writeDouble("scale4", scale4, props);
writeDouble("offset4", offset4, props);
writeDouble("scale6", scale6, props);
writeDouble("offset6", offset6, props);
}
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readDouble("low", "setLow", props);
readDouble("high", "setHigh", props);
readLong("samples", "setSamples", props);
readDouble("sampleScale", "setSampleScale", props);
readBoolean("locked", "setLocked", props);
if (locked) {
scale2 = props.getAsDouble("scale2");
offset2 = props.getAsDouble("offset2");
scale3 = props.getAsDouble("scale3");
offset3 = props.getAsDouble("offset3");
scale4 = props.getAsDouble("scale4");
offset4 = props.getAsDouble("offset4");
scale6 = props.getAsDouble("scale6");
offset6 = props.getAsDouble("offset6");
}
readSource(props, map);
calculate();
return this;
}
}

View File

@@ -0,0 +1,334 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
import com.sudoplay.joise.generator.LCG;
import com.sudoplay.joise.noise.Interpolator;
import com.sudoplay.joise.noise.Noise;
public class ModuleBasisFunction extends SeedableModule {
public enum BasisType {
VALUE, GRADIENT, GRADVAL, SIMPLEX, WHITE
}
public enum InterpolationType {
NONE, LINEAR, CUBIC, QUINTIC
}
protected double[] scale = new double[4];
protected double[] offset = new double[4];
protected double[][] rotMatrix = new double[3][3];
protected double cos2d, sin2d;
protected Noise.Function2D func2D;
protected Noise.Function3D func3D;
protected Noise.Function4D func4D;
protected Noise.Function6D func6D;
protected Interpolator interpolator;
protected BasisType basisType;
protected InterpolationType interpolationType;
public ModuleBasisFunction() {
this(BasisType.GRADIENT, InterpolationType.QUINTIC, 10000);
}
public ModuleBasisFunction(BasisType type) {
this(type, InterpolationType.QUINTIC, 10000);
}
public ModuleBasisFunction(BasisType type, InterpolationType interpolationType) {
this(type, interpolationType, 10000);
}
public ModuleBasisFunction(BasisType type,
InterpolationType interpolationType, long seed) {
setType(type);
setInterpolation(interpolationType);
setSeed(seed);
}
public void setType(BasisType type) {
basisType = type;
switch (type) {
case GRADVAL:
func2D = Noise.Function2D.GRADVAL;
func3D = Noise.Function3D.GRADVAL;
func4D = Noise.Function4D.GRADVAL;
func6D = Noise.Function6D.GRADVAL;
break;
case SIMPLEX:
func2D = Noise.Function2D.SIMPLEX;
func3D = Noise.Function3D.SIMPLEX;
func4D = Noise.Function4D.SIMPLEX;
func6D = Noise.Function6D.SIMPLEX;
break;
case VALUE:
func2D = Noise.Function2D.VALUE;
func3D = Noise.Function3D.VALUE;
func4D = Noise.Function4D.VALUE;
func6D = Noise.Function6D.VALUE;
break;
case WHITE:
func2D = Noise.Function2D.WHITE;
func3D = Noise.Function3D.WHITE;
func4D = Noise.Function4D.WHITE;
func6D = Noise.Function6D.WHITE;
break;
case GRADIENT:
// fallthrough intentional
default:
func2D = Noise.Function2D.GRADIENT;
func3D = Noise.Function3D.GRADIENT;
func4D = Noise.Function4D.GRADIENT;
func6D = Noise.Function6D.GRADIENT;
break;
}
setMagicNumbers(type);
}
public BasisType getBasisType() {
return basisType;
}
public void setInterpolation(InterpolationType type) {
interpolationType = type;
switch (type) {
case CUBIC:
this.interpolator = Interpolator.HERMITE;
break;
case LINEAR:
this.interpolator = Interpolator.LINEAR;
break;
case NONE:
this.interpolator = Interpolator.NONE;
break;
default:
this.interpolator = Interpolator.QUINTIC;
break;
}
}
public InterpolationType getInterpolationType() {
return interpolationType;
}
/**
* Set the rotation axis and angle to use for 3D, 4D and 6D noise.
*
* @param x
* @param y
* @param z
* @param angle
*/
public void setRotationAngle(double x, double y, double z, double angle) {
double sin = Math.sin(angle);
double cos = Math.cos(angle);
rotMatrix[0][0] = 1 + (1 - cos) * (x * x - 1);
rotMatrix[1][0] = -z * sin + (1 - cos) * x * y;
rotMatrix[2][0] = y * sin + (1 - cos) * x * z;
rotMatrix[0][1] = z * sin + (1 - cos) * x * y;
rotMatrix[1][1] = 1 + (1 - cos) * (y * y - 1);
rotMatrix[2][1] = -x * sin + (1 - cos) * y * z;
rotMatrix[0][2] = -y * sin + (1 - cos) * x * z;
rotMatrix[1][2] = x * sin + (1 - cos) * y * z;
rotMatrix[2][2] = 1 + (1 - cos) * (z * z - 1);
}
@Override
public void setSeed(long seed) {
super.setSeed(seed);
LCG lcg = new LCG();
lcg.setSeed(seed);
double ax, ay, az;
double len;
ax = lcg.get01();
ay = lcg.get01();
az = lcg.get01();
len = Math.sqrt(ax * ax + ay * ay + az * az);
ax /= len;
ay /= len;
az /= len;
setRotationAngle(ax, ay, az, lcg.get01() * 3.141592 * 2.0);
double angle = lcg.get01() * 3.141592 * 2.0;
cos2d = Math.cos(angle);
sin2d = Math.sin(angle);
}
@Override
public double get(double x, double y) {
double nx, ny;
nx = x * cos2d - y * sin2d;
ny = y * cos2d + x * sin2d;
return func2D.get(nx, ny, seed, interpolator);
}
@Override
public double get(double x, double y, double z) {
double nx, ny, nz;
nx = (rotMatrix[0][0] * x) + (rotMatrix[1][0] * y) + (rotMatrix[2][0] * z);
ny = (rotMatrix[0][1] * x) + (rotMatrix[1][1] * y) + (rotMatrix[2][1] * z);
nz = (rotMatrix[0][2] * x) + (rotMatrix[1][2] * y) + (rotMatrix[2][2] * z);
return func3D.get(nx, ny, nz, seed, interpolator);
}
@Override
public double get(double x, double y, double z, double w) {
double nx, ny, nz;
nx = (rotMatrix[0][0] * x) + (rotMatrix[1][0] * y) + (rotMatrix[2][0] * z);
ny = (rotMatrix[0][1] * x) + (rotMatrix[1][1] * y) + (rotMatrix[2][1] * z);
nz = (rotMatrix[0][2] * x) + (rotMatrix[1][2] * y) + (rotMatrix[2][2] * z);
return func4D.get(nx, ny, nz, w, seed, interpolator);
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
double nx, ny, nz;
nx = (rotMatrix[0][0] * x) + (rotMatrix[1][0] * y) + (rotMatrix[2][0] * z);
ny = (rotMatrix[0][1] * x) + (rotMatrix[1][1] * y) + (rotMatrix[2][1] * z);
nz = (rotMatrix[0][2] * x) + (rotMatrix[1][2] * y) + (rotMatrix[2][2] * z);
return func6D.get(nx, ny, nz, w, u, v, seed, interpolator);
}
protected void setMagicNumbers(BasisType type) {
switch (type) {
case VALUE:
scale[0] = 1.0;
offset[0] = 0.0;
scale[1] = 1.0;
offset[1] = 0.0;
scale[2] = 1.0;
offset[2] = 0.0;
scale[3] = 1.0;
offset[3] = 0.0;
break;
case GRADIENT:
scale[0] = 1.86848;
offset[0] = -0.000118;
scale[1] = 1.85148;
offset[1] = -0.008272;
scale[2] = 1.64127;
offset[2] = -0.01527;
scale[3] = 1.92517;
offset[3] = 0.03393;
break;
case GRADVAL:
scale[0] = 0.6769;
offset[0] = -0.00151;
scale[1] = 0.6957;
offset[1] = -0.133;
scale[2] = 0.74622;
offset[2] = 0.01916;
scale[3] = 0.7961;
offset[3] = -0.0352;
break;
case WHITE:
scale[0] = 1.0;
offset[0] = 0.0;
scale[1] = 1.0;
offset[1] = 0.0;
scale[2] = 1.0;
offset[2] = 0.0;
scale[3] = 1.0;
offset[3] = 0.0;
break;
default:
scale[0] = 1.0;
offset[0] = 0.0;
scale[1] = 1.0;
offset[1] = 0.0;
scale[2] = 1.0;
offset[2] = 0.0;
scale[3] = 1.0;
offset[3] = 0.0;
break;
}
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeEnum("basis", getBasisType(), props);
writeEnum("interpolation", getInterpolationType(), props);
writeSeed(props);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readEnum("basis", "setType", BasisType.class, props);
readEnum("interpolation", "setInterpolation", InterpolationType.class,
props);
readSeed(props);
return this;
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import static com.sudoplay.joise.noise.Util.bias;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleBias extends SourcedModule {
protected ScalarParameter bias = new ScalarParameter(0.5);
public ModuleBias() {}
public ModuleBias(double bias) {
this.bias.set(bias);
}
public ModuleBias(Module bias) {
this.bias.set(bias);
}
public void setBias(double bias) {
this.bias.set(bias);
}
public void setBias(Module bias) {
this.bias.set(bias);
}
@Override
public double get(double x, double y) {
double val = source.get(x, y);
return bias(bias.get(x, y), val);
}
@Override
public double get(double x, double y, double z) {
double val = source.get(x, y, z);
return bias(bias.get(x, y, z), val);
}
@Override
public double get(double x, double y, double z, double w) {
double val = source.get(x, y, z, w);
return bias(bias.get(x, y, z, w), val);
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
double val = source.get(x, y, z, w, u, v);
return bias(bias.get(x, y, z, w, u, v), val);
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeScalar("bias", bias, props, map);
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readScalar("bias", "setBias", props, map);
readSource(props, map);
return this;
}
}

View File

@@ -0,0 +1,144 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import static com.sudoplay.joise.noise.Util.lerp;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleBlend extends Module {
protected ScalarParameter low = new ScalarParameter(0.0);
protected ScalarParameter high = new ScalarParameter(1.0);
protected ScalarParameter control = new ScalarParameter(0.5);
public void setLowSource(Module source) {
low.set(source);
}
public void setLowSource(double source) {
low.set(source);
}
public void setHighSource(Module source) {
high.set(source);
}
public void setHighSource(double source) {
high.set(source);
}
public void setControlSource(Module source) {
control.set(source);
}
public void setControlSource(double source) {
control.set(source);
}
@Override
public double get(double x, double y) {
double v1 = low.get(x, y);
double v2 = high.get(x, y);
double bl = control.get(x, y);
bl = (bl + 1.0) * 0.5;
return lerp(bl, v1, v2);
}
@Override
public double get(double x, double y, double z) {
double v1 = low.get(x, y, z);
double v2 = high.get(x, y, z);
double bl = control.get(x, y, z);
return lerp(bl, v1, v2);
}
@Override
public double get(double x, double y, double z, double w) {
double v1 = low.get(x, y, z, w);
double v2 = high.get(x, y, z, w);
double bl = control.get(x, y, z, w);
return lerp(bl, v1, v2);
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
double v1 = low.get(x, y, z, w, u, v);
double v2 = high.get(x, y, z, w, u, v);
double bl = control.get(x, y, z, w, u, v);
return lerp(bl, v1, v2);
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeScalar("high", high, props, map);
writeScalar("low", low, props, map);
writeScalar("control", control, props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readScalar("high", "setHighSource", props, map);
readScalar("low", "setLowSource", props, map);
readScalar("control", "setControlSource", props, map);
return this;
}
}

View File

@@ -0,0 +1,163 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleBrightContrast extends SourcedModule {
protected ScalarParameter bright = new ScalarParameter(0.0);
protected ScalarParameter threshold = new ScalarParameter(0.0);
protected ScalarParameter factor = new ScalarParameter(1.0);
public void setBrightness(double b) {
bright.set(b);
}
public void setBrightness(Module source) {
bright.set(source);
}
public void setContrastThreshold(double t) {
threshold.set(t);
}
public void setContrastThreshold(Module source) {
threshold.set(source);
}
public void setContrastFactor(double f) {
factor.set(f);
}
public void setContrastFactor(Module source) {
factor.set(source);
}
@Override
public double get(double x, double y) {
double val = source.get(x, y);
// apply brightness
val += bright.get(x, y);
// subtract threshold, scale by factor, add threshold
double t = threshold.get(x, y);
val -= t;
val *= factor.get(x, y);
val += t;
return val;
}
@Override
public double get(double x, double y, double z) {
double val = source.get(x, y, z);
// apply brightness
val += bright.get(x, y, z);
// subtract threshold, scale by factor, add threshold
double t = threshold.get(x, y, z);
val -= t;
val *= factor.get(x, y, z);
val += t;
return val;
}
@Override
public double get(double x, double y, double z, double w) {
double val = source.get(x, y, z, w);
// apply brightness
val += bright.get(x, y, z, w);
// subtract threshold, scale by factor, add threshold
double t = threshold.get(x, y, z, w);
val -= t;
val *= factor.get(x, y, z, w);
val += t;
return val;
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
double val = source.get(x, y, z, w, u, v);
// apply brightness
val += bright.get(x, y, z, w, u, v);
// subtract threshold, scale by factor, add threshold
double t = threshold.get(x, y, z, w, u, v);
val -= t;
val *= factor.get(x, y, z, w, u, v);
val += t;
return val;
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeScalar("brightness", bright, props, map);
writeScalar("contrastFactor", factor, props, map);
writeScalar("contrastThreshold", threshold, props, map);
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readScalar("brightness", "setBrightness", props, map);
readScalar("contrastFactor", "setContrastFactor", props, map);
readScalar("contrastThreshold", "setContrastThreshold", props, map);
readSource(props, map);
return this;
}
}

View File

@@ -0,0 +1,140 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleCache extends SourcedModule {
class Cache {
double x, y, z, w, u, v;
double val;
boolean valid = false;
}
protected Cache c2 = new Cache();
protected Cache c3 = new Cache();
protected Cache c4 = new Cache();
protected Cache c6 = new Cache();
@Override
public double get(double x, double y) {
if (!c2.valid || c2.x != x || c2.y != y) {
c2.x = x;
c2.y = y;
c2.valid = true;
c2.val = source.get(x, y);
}
return c2.val;
}
@Override
public double get(double x, double y, double z) {
if (!c3.valid || c3.x != x || c3.y != y || c3.z != z) {
c3.x = x;
c3.y = y;
c3.z = z;
c3.valid = true;
c3.val = source.get(x, y, z);
}
return c3.val;
}
@Override
public double get(double x, double y, double z, double w) {
if (!c4.valid || c4.x != x || c4.y != y || c4.z != z || c4.w != w) {
c4.x = x;
c4.y = y;
c4.z = z;
c4.w = w;
c4.valid = true;
c4.val = source.get(x, y, z, w);
}
return c4.val;
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
if (!c6.valid || c6.x != x || c6.y != y || c6.z != z || c6.w != w
|| c6.u != u || c6.v != v) {
c6.x = x;
c6.y = y;
c6.z = z;
c6.w = w;
c6.u = u;
c6.v = v;
c6.valid = true;
c6.val = source.get(x, y, z, w, u, v);
}
return c6.val;
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readSource(props, map);
return this;
}
}

View File

@@ -0,0 +1,176 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
import com.sudoplay.joise.noise.Noise;
public class ModuleCellGen extends SeedableModule {
private int id = Module.nextId.incrementAndGet();
public class CellularCache {
double[] f = new double[4];
double[] d = new double[4];
double x, y, z, w, u, v;
boolean valid = false;
}
protected CellularCache c2 = new CellularCache();
protected CellularCache c3 = new CellularCache();
protected CellularCache c4 = new CellularCache();
protected CellularCache c6 = new CellularCache();
@Override
public String getId() {
return "func_" + id;
}
@Override
public void setSeed(long seed) {
super.setSeed(seed);
c2.valid = false;
c3.valid = false;
c4.valid = false;
c6.valid = false;
}
public CellularCache getCache(double x, double y) {
if (!c2.valid || c2.x != x || c2.y != y) {
Noise.cellularFunction2D(x, y, seed, c2.f, c2.d);
c2.x = x;
c2.y = y;
c2.valid = true;
}
return c2;
}
public CellularCache getCache(double x, double y, double z) {
if (!c3.valid || c3.x != x || c3.y != y || c3.z != z) {
Noise.cellularFunction3D(x, y, z, seed, c3.f, c3.d);
c3.x = x;
c3.y = y;
c3.z = z;
c3.valid = true;
}
return c3;
}
public CellularCache getCache(double x, double y, double z, double w) {
if (!c4.valid || c4.x != x || c4.y != y || c4.z != z || c4.w != w) {
Noise.cellularFunction4D(x, y, z, w, seed, c4.f, c4.d);
c4.x = x;
c4.y = y;
c4.z = z;
c4.w = w;
c4.valid = true;
}
return c4;
}
public CellularCache getCache(double x, double y, double z, double w,
double u, double v) {
if (!c6.valid || c6.x != x || c6.y != y || c6.z != z || c6.w != w
|| c6.u != u || c6.v != v) {
Noise.cellularFunction6D(x, y, z, w, u, v, seed, c6.f, c6.d);
c6.x = x;
c6.y = y;
c6.z = z;
c6.w = w;
c6.u = u;
c6.v = v;
c6.valid = true;
}
return c6;
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeSeed(props);
map.put(getId(), props);
}
@Override
public ModuleCellGen buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readSeed(props);
return this;
}
@Override
public double get(double x, double y) {
throw new UnsupportedOperationException();
}
@Override
public double get(double x, double y, double z) {
throw new UnsupportedOperationException();
}
@Override
public double get(double x, double y, double z, double w) {
throw new UnsupportedOperationException();
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,161 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
import com.sudoplay.joise.module.ModuleCellGen.CellularCache;
public class ModuleCellular extends Module {
protected double[] coefficients = new double[4];
protected ModuleCellGen generator;
public ModuleCellular() {
setCoefficients(1, 0, 0, 0);
}
public void setCellularSource(ModuleCellGen generator) {
this.generator = generator;
}
public void setCoefficients(double a, double b, double c, double d) {
coefficients[0] = a;
coefficients[1] = b;
coefficients[2] = c;
coefficients[3] = d;
}
public void setCoefficient(int index, double val) {
if (index > 3 || index < 0) {
throw new IllegalArgumentException();
}
coefficients[index] = val;
}
@Override
public double get(double x, double y) {
if (generator == null) {
return 0.0;
}
CellularCache c = generator.getCache(x, y);
return c.f[0] * coefficients[0] + c.f[1] * coefficients[1] + c.f[2]
* coefficients[2] + c.f[3] * coefficients[3];
}
@Override
public double get(double x, double y, double z) {
if (generator == null) {
return 0.0;
}
CellularCache c = generator.getCache(x, y, z);
return c.f[0] * coefficients[0] + c.f[1] * coefficients[1] + c.f[2]
* coefficients[2] + c.f[3] * coefficients[3];
}
@Override
public double get(double x, double y, double z, double w) {
if (generator == null) {
return 0.0;
}
CellularCache c = generator.getCache(x, y, z, w);
return c.f[0] * coefficients[0] + c.f[1] * coefficients[1] + c.f[2]
* coefficients[2] + c.f[3] * coefficients[3];
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
if (generator == null) {
return 0.0;
}
CellularCache c = generator.getCache(x, y, z, w, u, v);
return c.f[0] * coefficients[0] + c.f[1] * coefficients[1] + c.f[2]
* coefficients[2] + c.f[3] * coefficients[3];
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
if (generator != null) {
props.put("generator", generator.getId());
generator._writeToMap(map);
} else {
props.put("generator", 0);
}
StringBuilder sb = new StringBuilder();
for (double d : coefficients) {
sb.append(String.valueOf(d)).append(" ");
}
props.put("coefficients", sb.toString().trim());
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
String coeff = props.getAsString("coefficients");
String[] arr = coeff.split(" ");
for (int i = 0; i < 4; i++) {
coefficients[i] = Double.parseDouble(arr[i]);
}
String gen = props.getAsString("generator");
setCellularSource((ModuleCellGen) map.get(gen));
return this;
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import static com.sudoplay.joise.noise.Util.clamp;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleClamp extends SourcedModule {
protected double low;
protected double high;
public ModuleClamp() {
setRange(-1.0, 1.0);
}
public ModuleClamp(double low, double high) {
setRange(low, high);
}
public void setRange(double low, double high) {
this.low = low;
this.high = high;
}
public void setLow(double low) {
this.low = low;
}
public void setHigh(double high) {
this.high = high;
}
@Override
public double get(double x, double y) {
return clamp(source.get(x, y), low, high);
}
@Override
public double get(double x, double y, double z) {
return clamp(source.get(x, y, z), low, high);
}
@Override
public double get(double x, double y, double z, double w) {
return clamp(source.get(x, y, z, w), low, high);
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
return clamp(source.get(x, y, z, w, u, v), low, high);
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeDouble("low", low, props);
writeDouble("high", high, props);
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readDouble("low", "setLow", props);
readDouble("high", "setHigh", props);
readSource(props, map);
return this;
}
}

View File

@@ -0,0 +1,489 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleCombiner extends Module {
public static enum CombinerType {
ADD, MULT, MAX, MIN, AVG
}
protected ScalarParameter[] sources = new ScalarParameter[MAX_SOURCES];
protected CombinerType type;
public ModuleCombiner(CombinerType type) {
setType(type);
}
public ModuleCombiner() {
// serialization
}
public void setType(CombinerType type) {
this.type = type;
}
public void setSource(int index, Module source) {
sources[index] = new ScalarParameter(source);
}
public void setSource(int index, double source) {
sources[index] = new ScalarParameter(source);
}
public void clearAllSources() {
for (int i = 0; i < MAX_SOURCES; i++) {
sources[i] = null;
}
}
@Override
public double get(double x, double y) {
switch (type) {
case ADD:
return addGet(x, y);
case AVG:
return avgGet(x, y);
case MAX:
return maxGet(x, y);
case MIN:
return minGet(x, y);
case MULT:
return multGet(x, y);
default:
return 0.0;
}
}
@Override
public double get(double x, double y, double z) {
switch (type) {
case ADD:
return addGet(x, y, z);
case AVG:
return avgGet(x, y, z);
case MAX:
return maxGet(x, y, z);
case MIN:
return minGet(x, y, z);
case MULT:
return multGet(x, y, z);
default:
return 0.0;
}
}
@Override
public double get(double x, double y, double z, double w) {
switch (type) {
case ADD:
return addGet(x, y, z, w);
case AVG:
return avgGet(x, y, z, w);
case MAX:
return maxGet(x, y, z, w);
case MIN:
return minGet(x, y, z, w);
case MULT:
return multGet(x, y, z, w);
default:
return 0.0;
}
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
switch (type) {
case ADD:
return addGet(x, y, z, w, u, v);
case AVG:
return avgGet(x, y, z, w, u, v);
case MAX:
return maxGet(x, y, z, w, u, v);
case MIN:
return minGet(x, y, z, w, u, v);
case MULT:
return multGet(x, y, z, w, u, v);
default:
return 0.0;
}
}
// ==========================================================================
// = ADD
// ==========================================================================
protected double addGet(double x, double y) {
double value = 0.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value += sources[i].get(x, y);
}
return value;
}
protected double addGet(double x, double y, double z) {
double value = 0.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value += sources[i].get(x, y, z);
}
return value;
}
protected double addGet(double x, double y, double z, double w) {
double value = 0.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value += sources[i].get(x, y, z, w);
}
return value;
}
protected double addGet(double x, double y, double z, double w, double u,
double v) {
double value = 0.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value += sources[i].get(x, y, z, w, u, v);
}
return value;
}
// ==========================================================================
// = AVG
// ==========================================================================
protected double avgGet(double x, double y) {
int count = 0;
double value = 0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) {
value += sources[i].get(x, y);
count++;
}
}
if (count == 0) return 0.0;
return value / (double) count;
}
protected double avgGet(double x, double y, double z) {
int count = 0;
double value = 0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) {
value += sources[i].get(x, y, z);
count++;
}
}
if (count == 0) return 0.0;
return value / (double) count;
}
protected double avgGet(double x, double y, double z, double w) {
int count = 0;
double value = 0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) {
value += sources[i].get(x, y, z, w);
count++;
}
}
if (count == 0) return 0.0;
return value / (double) count;
}
protected double avgGet(double x, double y, double z, double w, double u,
double v) {
int count = 0;
double value = 0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) {
value += sources[i].get(x, y, z, w, u, v);
count++;
}
}
if (count == 0) return 0.0;
return value / (double) count;
}
// ==========================================================================
// = MAX
// ==========================================================================
protected double maxGet(double x, double y) {
double mx;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mx = sources[c].get(x, y);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y);
if (val > mx) mx = val;
}
}
return mx;
}
protected double maxGet(double x, double y, double z) {
double mx;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mx = sources[c].get(x, y, z);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y, z);
if (val > mx) mx = val;
}
}
return mx;
}
protected double maxGet(double x, double y, double z, double w) {
double mx;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mx = sources[c].get(x, y, z, w);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y, z, w);
if (val > mx) mx = val;
}
}
return mx;
}
protected double maxGet(double x, double y, double z, double w, double u,
double v) {
double mx;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mx = sources[c].get(x, y, z, w, u, v);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y, z, w, u, v);
if (val > mx) mx = val;
}
}
return mx;
}
// ==========================================================================
// = MIN
// ==========================================================================
protected double minGet(double x, double y) {
double mn;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mn = sources[c].get(x, y);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y);
if (val < mn) mn = val;
}
}
return mn;
}
protected double minGet(double x, double y, double z) {
double mn;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mn = sources[c].get(x, y, z);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y, z);
if (val < mn) mn = val;
}
}
return mn;
}
protected double minGet(double x, double y, double z, double w) {
double mn;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mn = sources[c].get(x, y, z, w);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y, z, w);
if (val < mn) mn = val;
}
}
return mn;
}
protected double minGet(double x, double y, double z, double w, double u,
double v) {
double mn;
int c = 0;
while (c < MAX_SOURCES && sources[c] == null) {
c++;
}
if (c == MAX_SOURCES) return 0.0;
mn = sources[c].get(x, y, z, w, u, v);
for (int d = c; d < MAX_SOURCES; d++) {
if (sources[d] != null) {
double val = sources[d].get(x, y, z, w, u, v);
if (val < mn) mn = val;
}
}
return mn;
}
// ==========================================================================
// = MULT
// ==========================================================================
protected double multGet(double x, double y) {
double value = 1.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value *= sources[i].get(x, y);
}
return value;
}
protected double multGet(double x, double y, double z) {
double value = 1.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value *= sources[i].get(x, y, z);
}
return value;
}
protected double multGet(double x, double y, double z, double w) {
double value = 1.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value *= sources[i].get(x, y, z, w);
}
return value;
}
protected double multGet(double x, double y, double z, double w, double u,
double v) {
double value = 1.0;
for (int i = 0; i < MAX_SOURCES; i++) {
if (sources[i] != null) value *= sources[i].get(x, y, z, w, u, v);
}
return value;
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeEnum("type", type, props);
for (int i = 0; i < MAX_SOURCES; i++) {
writeScalar("source" + i, sources[i], props, map);
}
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readEnum("type", "setType", CombinerType.class, props);
String name;
Object o;
for (int i = 0; i < MAX_SOURCES; i++) {
o = props.get("source" + i);
if (o != null) {
name = o.toString();
setSource(i, map.get(name));
}
}
return this;
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright (C) 2013 Jason Taylor.
* Released as open-source under the Apache License, Version 2.0.
*
* ============================================================================
* | Joise
* ============================================================================
*
* Copyright (C) 2013 Jason Taylor
*
* 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.
*
* ============================================================================
* | Accidental Noise Library
* | --------------------------------------------------------------------------
* | Joise is a derivative work based on Josua Tippetts' C++ library:
* | http://accidentalnoise.sourceforge.net/index.html
* ============================================================================
*
* Copyright (C) 2011 Joshua Tippetts
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package com.sudoplay.joise.module;
import com.sudoplay.joise.ModuleInstanceMap;
import com.sudoplay.joise.ModuleMap;
import com.sudoplay.joise.ModulePropertyMap;
public class ModuleCos extends SourcedModule {
@Override
public double get(double x, double y) {
return Math.cos(source.get(x, y));
}
@Override
public double get(double x, double y, double z) {
return Math.cos(source.get(x, y, z));
}
@Override
public double get(double x, double y, double z, double w) {
return Math.cos(source.get(x, y, z, w));
}
@Override
public double get(double x, double y, double z, double w, double u, double v) {
return Math.cos(source.get(x, y, z, w, u, v));
}
@Override
protected void _writeToMap(ModuleMap map) {
ModulePropertyMap props = new ModulePropertyMap(this);
writeSource(props, map);
map.put(getId(), props);
}
@Override
public Module buildFromPropertyMap(ModulePropertyMap props,
ModuleInstanceMap map) {
readSource(props, map);
return this;
}
}

Some files were not shown because too many files have changed in this diff Show More