Fixed up some textures, start working on a CTM rewrite

This commit is contained in:
aidancbrady committed 2016-05-05 22:52:57 -04:00
1 parent c29e4ab9bc
commit 840af06f43
23 files changed
+1755 -28

No files matched your search

@@ -0,0 +1,24 @@
package mekanism.client.render.ctm;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.IBlockAccess;
public class BlockRenderTypeCTM {
public ChiselTextureCTM makeTexture(EnumWorldBlockLayer layer, TextureSpriteCallback... sprites) {
return new ChiselTextureCTM(this, layer, sprites);
}
public CTMBlockRenderContext getBlockRenderContext(IBlockAccess world, BlockPos pos) {
return new CTMBlockRenderContext(world, pos);
}
public int getQuadsPerSide() {
return 4;
}
public int requiredTextures() {
return 2;
}
}
@@ -0,0 +1,299 @@
package mekanism.client.render.ctm;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.EnumMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import static mekanism.client.render.ctm.Dir.*;
// @formatter:off
/**
* The CTM renderer will draw the block's FACE using by assembling 4 quadrants from the 5 available block
* textures. The normal Texture.png is the blocks "unconnected" texture, and is used when CTM is disabled or the block
* has nothing to connect to. This texture has all of the outside corner quadrants The texture-ctm.png contains the
* rest of the quadrants.
* <pre><blockquote>
* ┌─────────────────┐ ┌────────────────────────────────┐
* │ texture.png │ │ texture-ctm.png │
* │ ╔══════╤══════╗ │ │ ──────┼────── ║ ─────┼───── ║ │
* │ ║ │ ║ │ │ │ │ │║ │ ║ │
* │ ║ 16 │ 17 ║ │ │ │ 0 │ 1 │║ 2 │ 3 ║ │
* │ ╟──────┼──────╢ │ │ ┼──────┼──────┼╟──────┼──────╢ │
* │ ║ │ ║ │ │ │ │ │║ │ ║ │
* │ ║ 18 │ 19 ║ │ │ │ 4 │ 5 │║ 6 │ 7 ║ │
* │ ╚══════╧══════╝ │ │ ──────┼────── ║ ─────┼───── ║ │
* └─────────────────┘ │ ═══════╤═══════╝ ─────┼───── ╚ │
* │ │ │ ││ │ │ │
* │ │ 8 │ 9 ││ 10 │ 11 │ │
* │ ┼──────┼──────┼┼──────┼──────┼ │
* │ │ │ ││ │ │ │
* │ │ 12 │ 13 ││ 14 │ 15 │ │
* │ ═══════╧═══════╗ ─────┼───── ╔ │
* └────────────────────────────────┘
* </blockquote></pre>
* combining { 18, 13, 9, 16 }, we can generate a texture connected to the right!
* <pre><blockquote>
* ╔══════╤═══════
* ║ │ │
* ║ 16 │ 9 │
* ╟──────┼──────┼
* ║ │ │
* ║ 18 │ 13 │
* ╚══════╧═══════
* </blockquote></pre>
*
* combining { 18, 13, 11, 2 }, we can generate a texture, in the shape of an L (connected to the right, and up
* <pre><blockquote>
* ║ ─────┼───── ╚
* ║ │ │
* ║ 2 │ 11 │
* ╟──────┼──────┼
* ║ │ │
* ║ 18 │ 13 │
* ╚══════╧═══════
* </blockquote></pre>
*
* HAVE FUN!
* -CptRageToaster-
*/
public class CTM {
/**
* The Uvs for the specific "magic number" value
*/
public static final ISubmap[] uvs = new ISubmap[]{
//Ctm texture
new Submap(4, 4, 0, 0), // 0
new Submap(4, 4, 4, 0), // 1
new Submap(4, 4, 8, 0), // 2
new Submap(4, 4, 12, 0), // 3
new Submap(4, 4, 0, 4), // 4
new Submap(4, 4, 4, 4), // 5
new Submap(4, 4, 8, 4), // 6
new Submap(4, 4, 12, 4), // 7
new Submap(4, 4, 0, 8), // 8
new Submap(4, 4, 4, 8), // 9
new Submap(4, 4, 8, 8), // 10
new Submap(4, 4, 12, 8), // 11
new Submap(4, 4, 0, 12), // 12
new Submap(4, 4, 4, 12), // 13
new Submap(4, 4, 8, 12), // 14
new Submap(4, 4, 12, 12), // 15
// Default texture
new Submap(8, 8, 0, 0), // 16
new Submap(8, 8, 8, 0), // 17
new Submap(8, 8, 0, 8), // 18
new Submap(8, 8, 8, 8) // 19
};
public static final ISubmap FULL_TEXTURE = new Submap(16, 16, 0, 0);
// @formatter:on
/** Some hardcoded offset values for the different corner indeces */
protected static int[] submapOffsets = { 4, 5, 1, 0 };
/** For use via the Chisel 2 config only, altering this could cause unintended behavior */
public static boolean disableObscuredFaceCheckConfig = false;
public Optional<Boolean> disableObscuredFaceCheck = Optional.absent();
protected TIntObjectMap<Dir[]> submapMap = new TIntObjectHashMap<Dir[]>();
protected EnumMap<Dir, Boolean> connectionMap = Maps.newEnumMap(Dir.class);
protected int[] submapCache;
protected CTM() {
for (Dir dir : Dir.VALUES) {
connectionMap.put(dir, false);
}
// Mapping the different corner indeces to their respective dirs
submapMap.put(0, new Dir[] { BOTTOM, LEFT, BOTTOM_LEFT });
submapMap.put(1, new Dir[] { BOTTOM, RIGHT, BOTTOM_RIGHT });
submapMap.put(2, new Dir[] { TOP, RIGHT, TOP_RIGHT });
submapMap.put(3, new Dir[] { TOP, LEFT, TOP_LEFT });
}
public static CTM getInstance() {
return new CTM();
}
/**
* @return The indeces of the typical 4x4 submap to use for the given face at the given location.
*
* Indeces are in counter-clockwise order starting at bottom left.
*/
public int[] createSubmapIndices(IBlockAccess world, BlockPos pos, EnumFacing side) {
submapCache = new int[] { 18, 19, 17, 16 };
if (world == null) {
return submapCache;
}
buildConnectionMap(world, pos, side);
// Map connections to submap indeces
for (int i = 0; i < 4; i++) {
fillSubmaps(i);
}
return submapCache;
}
public int[] getSubmapIndices() {
return submapCache;
}
public static boolean isDefaultTexture(int id) {
return (id == 16 || id == 17 || id == 18 || id == 19);
}
/**
* Builds the connection map and stores it in this CTM instance. The {@link #connected(Dir)}, {@link #connectedAnd(Dir...)}, and {@link #connectedOr(Dir...)} methods can be used to access it.
*/
public void buildConnectionMap(IBlockAccess world, BlockPos pos, EnumFacing side) {
IBlockState state = world.getBlockState(pos);
for (Dir dir : Dir.VALUES) {
connectionMap.put(dir, dir.isConnected(this, world, pos, side, state));
}
}
private void fillSubmaps(int idx) {
Dir[] dirs = submapMap.get(idx);
if (connectedOr(dirs[0], dirs[1])) {
if (connectedAnd(dirs)) {
// If all dirs are connected, we use the fully connected face,
// the base offset value.
submapCache[idx] = submapOffsets[idx];
} else {
// This is a bit magic-y, but basically the array is ordered so
// the first dir requires an offset of 2, and the second dir
// requires an offset of 8, plus the initial offset for the
// corner.
submapCache[idx] = submapOffsets[idx] + (connected(dirs[0]) ? 2 : 0) + (connected(dirs[1]) ? 8 : 0);
}
}
}
/**
* @param dir
* The direction to check connection in.
* @return True if the cached connectionMap holds a connection in this {@link Dir direction}.
*/
public boolean connected(Dir dir) {
return connectionMap.get(dir);
}
/**
* @param dirs
* The directions to check connection in.
* @return True if the cached connectionMap holds a connection in <i><b>all</b></i> the given {@link Dir directions}.
*/
public boolean connectedAnd(Dir... dirs) {
for (Dir dir : dirs) {
if (!connected(dir)) {
return false;
}
}
return true;
}
/**
* @param dirs
* The directions to check connection in.
* @return True if the cached connectionMap holds a connection in <i><b>one of</b></i> the given {@link Dir directions}.
*/
public boolean connectedOr(Dir... dirs) {
for (Dir dir : dirs) {
if (connected(dir)) {
return true;
}
}
return false;
}
/**
* A simple check for if the given block can connect to the given direction on the given side.
*
* @param world
* @param current
* The position of your block.
* @param y
* The position of the block to check against.
* @param dir
* The {@link EnumFacing side} of the block to check for connection status. This is <i>not</i> the direction to check in.
* @return True if the given block can connect to the given location on the given side.
*/
public boolean isConnected(IBlockAccess world, BlockPos current, BlockPos connection, EnumFacing dir) {
IBlockState state = world.getBlockState(current);
return isConnected(world, current, connection, dir, state);
}
/**
* A simple check for if the given block can connect to the given direction on the given side.
*
* @param world
* @param current
* The position of your block.
* @param y
* The position of the block to check against.
* @param dir
* The {@link EnumFacing side} of the block to check for connection status. This is <i>not</i> the direction to check in.
* @param state
* The state to check against for connection.
* @return True if the given block can connect to the given location on the given side.
*/
public boolean isConnected(IBlockAccess world, BlockPos current, BlockPos connection, EnumFacing dir, IBlockState state) {
// if (CTMLib.chiselLoaded() && connectionBlocked(world, x, y, z, dir.ordinal())) {
// return false;
// }
BlockPos pos2 = connection.add(dir.getDirectionVec());
boolean disableObscured = disableObscuredFaceCheck.or(disableObscuredFaceCheckConfig);
IBlockState con = getBlockOrFacade(world, connection, dir);
IBlockState obscuring = disableObscured ? null : getBlockOrFacade(world, pos2, dir);
// no block or a bad API user
if (con == null) {
return false;
}
// TODO VERY TEMPORARY
boolean ret = con.getBlock() == state.getBlock();
// no block obscuring this face
if (obscuring == null) {
return ret;
}
// check that we aren't already connected outwards from this side
ret &= !obscuring.getBlock().isFullCube() || !obscuring.equals(state);
return ret;
}
// private boolean connectionBlocked(IBlockAccess world, int x, int y, int z, int side) {
// Block block = world.getBlock(x, y, z);
// if (block instanceof IConnectable) {
// return !((IConnectable) block).canConnectCTM(world, x, y, z, side);
// }
// return false;
// }
public IBlockState getBlockOrFacade(IBlockAccess world, BlockPos pos, EnumFacing side) {
IBlockState state = world.getBlockState(pos);
return state;
}
}
@@ -0,0 +1,28 @@
package mekanism.client.render.ctm;
import java.util.EnumMap;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
public class CTMBlockRenderContext {
private EnumMap<EnumFacing, CTM> ctmData = new EnumMap<>(EnumFacing.class);
public CTMBlockRenderContext(IBlockAccess world, BlockPos pos) {
for (EnumFacing face : EnumFacing.VALUES) {
CTM ctm = createCTM();
ctm.createSubmapIndices(world, pos, face);
ctmData.put(face, ctm);
}
}
protected CTM createCTM() {
return CTM.getInstance();
}
public CTM getCTM(EnumFacing face) {
return ctmData.get(face);
}
}
@@ -0,0 +1,85 @@
package mekanism.client.render.ctm;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.util.ResourceLocation;
/**
* Chisel Face, basically a list of IChiselTexture's
*/
public final class ChiselFace {
private List<ChiselTextureCTM> textureList;
private List<ChiselFace> childFaces;
private ResourceLocation location;
private EnumWorldBlockLayer layer;
public ChiselFace(ResourceLocation location) {
this(new ArrayList<>(), new ArrayList<>(), location);
}
public ChiselFace(ResourceLocation location, EnumWorldBlockLayer layer) {
this(location);
setLayer(layer);
}
public ChiselFace(List<ChiselTextureCTM> textureList, List<ChiselFace> childFaces, ResourceLocation location) {
this.textureList = textureList;
this.childFaces = childFaces;
this.location = location;
}
public List<ChiselTextureCTM> getTextureList(){
List<ChiselTextureCTM> list = new ArrayList<>();
list.addAll(this.textureList);
for (ChiselFace face : childFaces){
list.addAll(face.getTextureList());
}
return list;
}
public void addTexture(ChiselTextureCTM texture){
this.textureList.add(texture);
}
public void addChildFace(ChiselFace face){
this.childFaces.add(face);
}
public boolean removeTexture(ChiselTextureCTM texture){
return this.textureList.remove(texture);
}
public boolean removeChildFace(ChiselFace face){
return this.childFaces.remove(face);
}
public TextureAtlasSprite getParticle(){
if (textureList.get(0) != null) {
return textureList.get(0).getParticle();
}
else {
return childFaces.get(0).getParticle();
}
}
public ResourceLocation getLocation(){
return this.location;
}
public void setLayer(EnumWorldBlockLayer layer){
this.layer = layer;
}
public EnumWorldBlockLayer getLayer(){
return this.layer;
}
}
@@ -0,0 +1,59 @@
package mekanism.client.render.ctm;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.Getter;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.util.ResourceLocation;
public class ChiselTextureCTM {
@Getter
protected BlockRenderTypeCTM type;
@Getter
protected EnumWorldBlockLayer layer;
protected TextureSpriteCallback[] sprites;
public ChiselTextureCTM(BlockRenderTypeCTM type, EnumWorldBlockLayer layer, TextureSpriteCallback[] sprites) {
this.type = type;
this.layer = layer;
this.sprites = sprites;
}
public List<BakedQuad> transformQuad(BakedQuad bq, CTMBlockRenderContext context, int quadGoal) {
Quad quad = Quad.from(bq, DefaultVertexFormats.ITEM);
if (context == null) {
return Collections.singletonList(quad.transformUVs(sprites[0].getSprite()).rebake());
}
Quad[] quads = quad.subdivide(4);
int[] ctm = ((CTMBlockRenderContext)context).getCTM(bq.getFace()).getSubmapIndices();
for (int i = 0; i < quads.length; i++) {
Quad q = quads[i];
if (q != null) {
int ctmid = q.getUvs().normalize().getQuadrant();
quads[i] = q.grow().transformUVs(sprites[ctm[ctmid] > 15 ? 0 : 1].getSprite(), CTM.uvs[ctm[ctmid]].normalize());
}
}
return Arrays.stream(quads).filter(Objects::nonNull).map(q -> q.rebake()).collect(Collectors.toList());
}
public TextureAtlasSprite getParticle(){
return sprites[0].getSprite();
}
public Collection<ResourceLocation> getTextures() {
return Arrays.stream(sprites).map(TextureSpriteCallback::getLocation).collect(Collectors.toList());
}
}
@@ -0,0 +1,186 @@
package mekanism.client.render.ctm;
import static net.minecraft.util.EnumFacing.DOWN;
import static net.minecraft.util.EnumFacing.EAST;
import static net.minecraft.util.EnumFacing.NORTH;
import static net.minecraft.util.EnumFacing.SOUTH;
import static net.minecraft.util.EnumFacing.UP;
import static net.minecraft.util.EnumFacing.WEST;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.EnumFacing.AxisDirection;
import net.minecraft.world.IBlockAccess;
import mekanism.client.render.ctm.CTM;
/**
* Think of this class as a "Two dimensional ForgeDirection, with diagonals".
* <p>
* It represents the eight different directions a face of a block can connect with CTM, and contains the logic for determining if a block is indeed connected in that direction.
* <p>
* Note that, for example, {@link #TOP_RIGHT} does not mean connected to the {@link #TOP} and {@link #RIGHT}, but connected in the diagonal direction represented by {@link #TOP_RIGHT}. This is used
* for inner corner rendering.
*/
public enum Dir {
// @formatter:off
TOP(UP),
TOP_RIGHT(UP, EAST),
RIGHT(EAST),
BOTTOM_RIGHT(DOWN, EAST),
BOTTOM(DOWN),
BOTTOM_LEFT(DOWN, WEST),
LEFT(WEST),
TOP_LEFT(UP, WEST);
// @formatter:on
/**
* All values of this enum, used to prevent unnecessary allocation via {@link #values()}.
*/
public static final Dir[] VALUES = values();
private static final EnumFacing NORMAL = SOUTH;
private EnumFacing[] dirs;
private Dir(EnumFacing... dirs) {
this.dirs = dirs;
}
/**
* Finds if this block is connected for the given side in this Dir.
*
* @param inst
* The CTM instance to use for logic.
* @param world
* The world the block is in.
* @param pos
* The position of your block.
* @param side
* The side of the current face.
* @return True if the block is connected in the given Dir, false otherwise.
*/
public boolean isConnected(CTM ctm, IBlockAccess world, BlockPos pos, EnumFacing side) {
return ctm.isConnected(world, pos, getConnection(pos, side), side);
}
/**
* Finds if this block is connected for the given side in this Dir.
*
* @param inst
* The CTM instance to use for logic.
* @param world
* The world the block is in.
* @param pos
* The position of your block.
* @param side
* The side of the current face.
* @param side
* The state to check for connection with.
* @return True if the block is connected in the given Dir, false otherwise.
*/
public boolean isConnected(CTM ctm, IBlockAccess world, BlockPos pos, EnumFacing side, IBlockState state) {
return ctm.isConnected(world, pos, getConnection(pos, side), side, state);
}
private BlockPos getConnection(BlockPos pos, EnumFacing side) {
EnumFacing[] dirs = getNormalizedDirs(side);
BlockPos connection = pos;
for (EnumFacing dir : dirs) {
connection = connection.offset(dir);
}
return connection;
}
private EnumFacing[] getNormalizedDirs(EnumFacing normal) {
if (normal == NORMAL) {
return dirs;
} else if (normal == NORMAL.getOpposite()) {
// If this is the opposite direction of the default normal, we
// need to mirror the dirs
// A mirror version does not affect y+ and y- so we ignore those
EnumFacing[] ret = new EnumFacing[dirs.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = dirs[i].getFrontOffsetY() != 0 ? dirs[i] : dirs[i].getOpposite();
}
return ret;
} else {
EnumFacing axis = null;
// Next, we need different a different rotation axis depending
// on if this is up/down or not
if (normal.getFrontOffsetY() == 0) {
// If it is not up/down, pick either the left or right-hand
// rotation
axis = normal == NORMAL.rotateY() ? UP : DOWN;
} else {
// If it is up/down, pick either the up or down rotation.
axis = normal == UP ? NORMAL.rotateYCCW() : NORMAL.rotateY();
}
EnumFacing[] ret = new EnumFacing[dirs.length];
// Finally apply all the rotations
for (int i = 0; i < ret.length; i++) {
ret[i] = rotate(dirs[i], axis);
}
return ret;
}
}
// God why
private static final int[] FACING_LOOKUP = new int[EnumFacing.values().length];
static {
FACING_LOOKUP[NORTH.ordinal()] = 1;
FACING_LOOKUP[EAST.ordinal()] = 2;
FACING_LOOKUP[SOUTH.ordinal()] = 3;
FACING_LOOKUP[WEST.ordinal()] = 4;
FACING_LOOKUP[UP.ordinal()] = 5;
FACING_LOOKUP[DOWN.ordinal()] = 6;
}
private EnumFacing rotate(EnumFacing facing, EnumFacing axisFacing) {
Axis axis = axisFacing.getAxis();
AxisDirection axisDir = axisFacing.getAxisDirection();
if (axisDir == AxisDirection.POSITIVE) {
return facing.rotateAround(axis);
}
if (facing.getAxis() != axis) {
switch (axis) {
case X:
// I did some manual testing and this is what worked...I don't get it either
switch (FACING_LOOKUP[facing.ordinal()]) {
case 1:
return NORTH;
case 2:
case 4:
default:
return facing; // Invalid but ignored
case 3:
return SOUTH;
case 5:
return SOUTH;
case 6:
return NORTH;
}
case Y:
return facing.rotateYCCW();
case Z:
switch (FACING_LOOKUP[facing.ordinal()]) {
case 2:
return EAST;
case 3:
default:
return facing; // invalid but ignored
case 4:
return WEST;
case 5:
return DOWN;
case 6:
return UP;
}
}
}
return facing;
}
}
@@ -0,0 +1,5 @@
package mekanism.client.render.ctm;
public interface ICTMBlock {
}
@@ -0,0 +1,24 @@
package mekanism.client.render.ctm;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
public interface ISubmap {
float getYOffset();
float getXOffset();
float getWidth();
float getHeight();
float getInterpolatedU(TextureAtlasSprite sprite, float u);
float getInterpolatedV(TextureAtlasSprite sprite, float v);
float[] toArray();
ISubmap normalize();
ISubmap relativize();
}
@@ -0,0 +1,143 @@
//package team.chisel.client.render.ctm;
//
//import team.chisel.common.block.BlockCarvable;
//import team.chisel.common.block.subblocks.ICTMSubBlock;
//import team.chisel.common.block.subblocks.ISubBlock;
//import team.chisel.common.connections.CTMConnections;
//import team.chisel.common.util.EnumConnection;
//import team.chisel.common.util.SubBlockUtil;
//import team.chisel.common.variation.PropertyVariation;
//import team.chisel.common.variation.Variation;
//import net.minecraft.block.state.IBlockState;
//import net.minecraft.client.renderer.block.model.BakedQuad;
//import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
//import net.minecraft.client.renderer.texture.TextureAtlasSprite;
//import net.minecraft.client.resources.model.IBakedModel;
//import net.minecraft.util.EnumFacing;
//import net.minecraftforge.client.model.ISmartBlockModel;
//import net.minecraftforge.common.property.IExtendedBlockState;
//
//import javax.vecmath.Vector3f;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Block Model for Connected textures
// * Deals with the Connected texture rendering basically
// *
// * @author minecreatr
// */
//public class ModelCTM implements ISmartBlockModel {
//
//
// private List<BakedQuad> quads;
//
// private TextureAtlasSprite particle;
//
//
// @Override
// public List getFaceQuads(EnumFacing face) {
// List<BakedQuad> toReturn = new ArrayList<BakedQuad>();
// for (BakedQuad quad : quads) {
// if (quad == null) {
// continue;
// }
// if (quad.getFace() == face) {
// toReturn.add(quad);
// }
// }
// return toReturn;
// }
//
// @Override
// public List getGeneralQuads() {
// return this.quads;
// }
//
// @Override
// public boolean isAmbientOcclusion() {
// return true;
// }
//
// @Override
// public boolean isGui3d() {
// return true;
// }
//
// @Override
// public boolean isBuiltInRenderer() {
// return false;
// }
//
// @Override
// public TextureAtlasSprite getTexture() {
// return particle;
// }
//
// @Override
// public ItemCameraTransforms getItemCameraTransforms() {
// return ItemCameraTransforms.DEFAULT;
// }
//
// @Override
// public IBakedModel handleBlockState(IBlockState state) {
// // /throw new RuntimeException(state.getValue(BlockCarvable.VARIATION).toString());
// PropertyVariation VARIATION = null;
// if (state.getBlock() instanceof BlockCarvable) {
// VARIATION = ((BlockCarvable) state.getBlock()).variation;
// }
// List<BakedQuad> newQuads = generateQuads(state, VARIATION);
// this.quads = newQuads;
// this.particle = SubBlockUtil.getResources(state.getBlock(), (Variation) state.getValue(VARIATION)).getDefaultTexture();
// return this;
// }
//
// private List<BakedQuad> generateQuads(IBlockState state, PropertyVariation VARIATION) {
// List<BakedQuad> newQuads = new ArrayList<BakedQuad>();
// Variation variation = (Variation) state.getValue(VARIATION);
// if (state.getBlock() instanceof BlockCarvable) {
// ISubBlock subBlock = ((BlockCarvable) state.getBlock()).getSubBlock(variation);
// if (subBlock instanceof ICTMSubBlock) {
// ICTMSubBlock ctmSubBlock = (ICTMSubBlock) subBlock;
// for (EnumFacing f : EnumFacing.values()) {
// if (!isTouchingSide(state, f)) {
// CTMFaceBakery.instance.makeCtmFace(f, ctmSubBlock.getResources(), CTM.getInstance().getSubmapIndices((IExtendedBlockState) state, f)).addToList(newQuads);
// }
// }
// }
// }
// return newQuads;
// }
//
// public static boolean isTouchingSide(IBlockState inState, EnumFacing f) {
// if (inState == null) {
// return false;
// }
// if (!(inState instanceof IExtendedBlockState)) {
// return false;
// }
// IExtendedBlockState state = (IExtendedBlockState) inState;
// CTMConnections connections = state.getValue(BlockCarvable.CONNECTIONS);
// if (connections.isConnected(EnumConnection.UP) && f == EnumFacing.UP) {
// return true;
// }
// if (connections.isConnected(EnumConnection.DOWN) && f == EnumFacing.DOWN) {
// return true;
// }
// if (connections.isConnected(EnumConnection.NORTH) && f == EnumFacing.NORTH) {
// return true;
// }
// if (connections.isConnected(EnumConnection.SOUTH) && f == EnumFacing.SOUTH) {
// return true;
// }
// if (connections.isConnected(EnumConnection.WEST) && f == EnumFacing.WEST) {
// return true;
// }
// if (connections.isConnected(EnumConnection.EAST) && f == EnumFacing.EAST) {
// return true;
// }
// return false;
// }
//
//
//}
@@ -0,0 +1,107 @@
package mekanism.client.render.ctm;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelBlockDefinition.Variant;
import net.minecraft.client.renderer.block.statemap.DefaultStateMapper;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.IModelState;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.TRSRTransformation;
import net.minecraftforge.common.property.IExtendedBlockState;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class ModelChisel implements IModel {
private static StateMapperBase mapper = new DefaultStateMapper();
private Variant model;
private Map<String, Variant> models = Maps.newHashMap();;
private String face;
private Map<EnumFacing, String> overrides = Maps.newHashMap();
private transient ChiselFace faceObj;
private transient Map<EnumFacing, ChiselFace> overridesObj = new EnumMap<>(EnumFacing.class);
private transient IBakedModel modelObj;
private transient Map<String, IBakedModel> modelsObj = Maps.newHashMap();
private transient Map<IBlockState, IBakedModel> stateMap = Maps.newHashMap();
private transient List<ResourceLocation> textures = Lists.newArrayList();
@Override
public Collection<ResourceLocation> getDependencies() {
List<ResourceLocation> list = Lists.newArrayList(model.getModelLocation());
list.addAll(models.values().stream().map(v -> v.getModelLocation()).collect(Collectors.toList()));
return list;
}
@Override
public Collection<ResourceLocation> getTextures() {
return ImmutableList.copyOf(textures);
}
@Override
@SneakyThrows
public IFlexibleBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {
Function<ResourceLocation, TextureAtlasSprite> dummyGetter = t -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(TextureMap.LOCATION_MISSING_TEXTURE.toString());
modelObj = ModelLoaderRegistry.getModel(model.getModelLocation()).bake(model.isUvLocked() ? new ModelLoader.UVLock(model.getState()) : model.getState(), format, dummyGetter);
for (Entry<String, Variant> e : models.entrySet()) {
Variant v = e.getValue();
modelsObj.put(e.getKey(), ModelLoaderRegistry.getModel(v.getModelLocation()).bake(v.isUvLocked() ? new ModelLoader.UVLock(v.getState()) : v.getState(), format, dummyGetter));
}
return new ModelChiselBlock(this);
}
@Override
public IModelState getDefaultState() {
return TRSRTransformation.identity();
}
public ChiselFace getDefaultFace() {
return faceObj;
}
public ChiselFace getFace(EnumFacing facing) {
return overridesObj.getOrDefault(facing, faceObj);
}
public IBakedModel getModel(IBlockState state) {
if (state instanceof IExtendedBlockState) {
state = ((IExtendedBlockState)state).getClean();
}
String stateStr = mapper.getPropertyString(state.getProperties());
stateStr = stateStr.substring(stateStr.indexOf(",") + 1, stateStr.length());
final String capture = stateStr;
if (modelsObj.containsKey(stateStr)) {
stateMap.computeIfAbsent(state, s -> modelsObj.get(capture));
}
return stateMap.getOrDefault(state, modelObj);
}
}
@@ -0,0 +1,156 @@
package mekanism.client.render.ctm;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
import mekanism.common.block.BlockBasic;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.Attributes;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.IPerspectiveAwareModel;
import net.minecraftforge.client.model.ISmartBlockModel;
import net.minecraftforge.client.model.ISmartItemModel;
import net.minecraftforge.client.model.TRSRTransformation;
import net.minecraftforge.common.property.IExtendedBlockState;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
/**
* Model for all chisel blocks
*/
@SuppressWarnings("deprecation")
public class ModelChiselBlock implements ISmartBlockModel, ISmartItemModel, IPerspectiveAwareModel {
public static final TRSRTransformation DEFAULT_BLOCK_THIRD_PERSON_TRANSOFRM = new TRSRTransformation(new Vector3f(0, 1.5f / 16f, -2.75f / 16f), TRSRTransformation.quatFromYXZDegrees(new Vector3f(10, -45, 170)), new Vector3f(0.375f, 0.375f, 0.375f), null);
public static final Matrix4f DEFAULT_BLOCK_THIRD_PERSON_MATRIX = DEFAULT_BLOCK_THIRD_PERSON_TRANSOFRM.getMatrix();
private List<BakedQuad> face;
private List<BakedQuad> general;
private ModelChisel model;
public ModelChiselBlock(List<BakedQuad> face, List<BakedQuad> general, ModelChisel model){
this.face = face;
this.general = general;
this.model = model;
}
public ModelChiselBlock(ModelChisel model){
this(Collections.emptyList(), Collections.emptyList(), model);
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing facing){
return FluentIterable.from(face).filter(quad -> quad.getFace() == facing).toList();
}
@Override
public List<BakedQuad> getGeneralQuads() {
return general;
}
@Override
public boolean isAmbientOcclusion(){
return true;
}
@Override
public boolean isGui3d(){
return true;
}
@Override
public boolean isBuiltInRenderer(){
return false;
}
@Override
public TextureAtlasSprite getParticleTexture() {
return this.model.getDefaultFace().getParticle();
}
@Override
public ItemCameraTransforms getItemCameraTransforms(){
return ItemCameraTransforms.DEFAULT;
}
// TODO implement model caching, returning a new model every time is a HUGE waste of memory and CPU
@Override
public IBakedModel handleBlockState(IBlockState stateIn) {
if (stateIn.getBlock() instanceof ICTMBlock && stateIn instanceof IExtendedBlockState) {
IExtendedBlockState state = (IExtendedBlockState) stateIn;
CTMBlockRenderContext ctxList = state.getValue(BlockBasic.ctmProperty);
return createModel(stateIn, model, ctxList);
} else {
return this;
}
}
@Override
public IBakedModel handleItemState(ItemStack stack) {
Block block = ((ItemBlock) stack.getItem()).getBlock();
return createModel(block.getDefaultState(), model, null);
}
private ModelChiselBlock createModel(IBlockState state, ModelChisel model, CTMBlockRenderContext ctx) {
List<BakedQuad> faceQuads = Lists.newArrayList();
List<BakedQuad> generalQuads = Lists.newArrayList();
for (EnumFacing facing : EnumFacing.VALUES){
ChiselFace face = model.getFace(facing);
int quadGoal = ctx == null ? 1 : Ordering.natural().max(FluentIterable.from(face.getTextureList()).transform(tex -> tex.getType().getQuadsPerSide()));
IBakedModel baked = model.getModel(state);
List<BakedQuad> origFaceQuads = baked.getFaceQuads(facing);
List<BakedQuad> origGeneralQuads = FluentIterable.from(baked.getGeneralQuads()).filter(q -> q.getFace() == facing).toList();
addAllQuads(origFaceQuads, face, ctx, quadGoal, faceQuads);
addAllQuads(origGeneralQuads, face, ctx, quadGoal, generalQuads);
}
return new ModelChiselBlock(faceQuads, generalQuads, model);
}
private void addAllQuads(List<BakedQuad> from, ChiselFace face, @Nullable CTMBlockRenderContext ctx, int quadGoal, List<BakedQuad> to) {
for (BakedQuad q : from) {
for (ChiselTextureCTM tex : face.getTextureList()) {
to.addAll(tex.transformQuad(q, ctx == null ? null : ctx, quadGoal));
}
}
}
@Override
public VertexFormat getFormat() {
return Attributes.DEFAULT_BAKED_FORMAT;
}
private Pair<IPerspectiveAwareModel, Matrix4f> thirdPersonTransform;
@Override
public Pair<? extends IFlexibleBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) {
if (cameraTransformType == TransformType.THIRD_PERSON) {
if (thirdPersonTransform == null) {
thirdPersonTransform = ImmutablePair.of(this, DEFAULT_BLOCK_THIRD_PERSON_MATRIX);
}
return thirdPersonTransform;
}
return Pair.of(this, null);
}
}
@@ -0,0 +1,29 @@
package mekanism.client.render.ctm;
import net.minecraftforge.common.property.IUnlistedProperty;
/**
* Block Property for the render context list
*/
public class PropertyCTMRenderContext implements IUnlistedProperty<CTMBlockRenderContext> {
@Override
public String getName(){
return "connections";
}
@Override
public boolean isValid(CTMBlockRenderContext value){
return true;
}
@Override
public Class<CTMBlockRenderContext> getType(){
return CTMBlockRenderContext.class;
}
@Override
public String valueToString(CTMBlockRenderContext value){
return value.toString();
}
}
@@ -0,0 +1,439 @@
package mekanism.client.render.ctm;
import java.util.List;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.Value;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.client.renderer.vertex.VertexFormatElement.EnumUsage;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
import org.apache.commons.lang3.tuple.Pair;
import org.lwjgl.util.vector.Vector;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MultimapBuilder;
@ToString(of = { "vertPos", "vertUv" })
public class Quad {
public static final ISubmap TOP_LEFT = new Submap(8, 8, 0, 0);
public static final ISubmap TOP_RIGHT = new Submap(8, 8, 8, 0);
public static final ISubmap BOTTOM_LEFT = new Submap(8, 8, 0, 8);
public static final ISubmap BOTTOM_RIGHT = new Submap(8, 8, 8, 8);
@Value
public static class Vertex {
Vector3f pos;
Vector2f uvs;
}
private static final TextureAtlasSprite BASE = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(TextureMap.LOCATION_MISSING_TEXTURE.toString());
@ToString
public class UVs {
@Getter
private float minU, minV, maxU, maxV;
@Getter
private final TextureAtlasSprite sprite;
private final Vector2f[] data;
private UVs(Vector2f... data) {
this(BASE, data);
}
private UVs(TextureAtlasSprite sprite, Vector2f... data) {
this.data = data;
this.sprite = sprite;
float minU = Float.MAX_VALUE;
float minV = Float.MAX_VALUE;
float maxU = 0, maxV = 0;
for (Vector2f v : data) {
minU = Math.min(minU, v.x);
minV = Math.min(minV, v.y);
maxU = Math.max(maxU, v.x);
maxV = Math.max(maxV, v.y);
}
this.minU = minU;
this.minV = minV;
this.maxU = maxU;
this.maxV = maxV;
}
public UVs(float minU, float minV, float maxU, float maxV, TextureAtlasSprite sprite) {
this.minU = minU;
this.minV = minV;
this.maxU = maxU;
this.maxV = maxV;
this.sprite = sprite;
this.data = vectorize();
}
public UVs transform(TextureAtlasSprite other, ISubmap submap) {
UVs normal = normalize();
submap = submap.normalize();
float width = normal.maxU - normal.minU;
float height = normal.maxV - normal.minV;
float minU = submap.getXOffset();
float minV = submap.getYOffset();
minU += normal.minU * submap.getWidth();
minV += normal.minV * submap.getHeight();
float maxU = minU + (width * submap.getWidth());
float maxV = minV + (height * submap.getHeight());
// TODO this is horrid
return new UVs(other,
new Vector2f(data[0].x == this.minU ? minU : maxU, data[0].y == this.minV ? minV : maxV),
new Vector2f(data[1].x == this.minU ? minU : maxU, data[1].y == this.minV ? minV : maxV),
new Vector2f(data[2].x == this.minU ? minU : maxU, data[2].y == this.minV ? minV : maxV),
new Vector2f(data[3].x == this.minU ? minU : maxU, data[3].y == this.minV ? minV : maxV))
.relativize();
}
UVs normalizeQuadrant() {
UVs normal = normalize();
int quadrant = normal.getQuadrant();
float minUInterp = quadrant == 1 || quadrant == 2 ? 0.5f : 0;
float minVInterp = quadrant < 2 ? 0.5f : 0;
float maxUInterp = quadrant == 0 || quadrant == 3 ? 0.5f : 1;
float maxVInterp = quadrant > 1 ? 0.5f : 1;
normal = new UVs(sprite, normalize(new Vector2f(minUInterp, minVInterp), new Vector2f(maxUInterp, maxVInterp), normal.vectorize()));
return normal.relativize();
}
public UVs normalize() {
Vector2f min = new Vector2f(sprite.getMinU(), sprite.getMinV());
Vector2f max = new Vector2f(sprite.getMaxU(), sprite.getMaxV());
return new UVs(sprite, normalize(min, max, data));
}
public UVs relativize() {
return relativize(sprite);
}
public UVs relativize(TextureAtlasSprite sprite) {
Vector2f min = new Vector2f(sprite.getMinU(), sprite.getMinV());
Vector2f max = new Vector2f(sprite.getMaxU(), sprite.getMaxV());
return new UVs(sprite, lerp(min, max, data));
}
public Vector2f[] vectorize() {
return data == null ? new Vector2f[]{ new Vector2f(minU, minV), new Vector2f(minU, maxV), new Vector2f(maxU, maxV), new Vector2f(maxU, minV) } : data;
}
private Vector2f[] normalize(Vector2f min, Vector2f max, Vector2f... vecs) {
Vector2f[] ret = new Vector2f[vecs.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = normalize(min, max, vecs[i]);
}
return ret;
}
private Vector2f normalize(Vector2f min, Vector2f max, Vector2f vec) {
return new Vector2f(Quad.normalize(min.x, max.x, vec.x), Quad.normalize(min.y, max.y, vec.y));
}
private Vector2f[] lerp(Vector2f min, Vector2f max, Vector2f... vecs) {
Vector2f[] ret = new Vector2f[vecs.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = lerp(min, max, vecs[i]);
}
return ret;
}
private Vector2f lerp(Vector2f min, Vector2f max, Vector2f vec) {
return new Vector2f(Quad.lerp(min.x, max.x, vec.x), Quad.lerp(min.y, max.y, vec.y));
}
public int getQuadrant() {
if (maxU <= 0.5f) {
if (maxV <= 0.5f) {
return 3;
} else {
return 0;
}
} else {
if (maxV <= 0.5f) {
return 2;
} else {
return 1;
}
}
}
}
private final Vector3f[] vertPos;
private final Vector2f[] vertUv;
// Technically nonfinal, but treated as such except in constructor
@Getter
private UVs uvs;
private final Builder builder;
private Quad(Vector3f[] verts, Vector2f[] uvs, Builder builder) {
this.vertPos = verts;
this.vertUv = uvs;
this.builder = builder;
this.uvs = new UVs(uvs);
}
private Quad(Vector3f[] verts, UVs uvs, Builder builder) {
this(verts, uvs.vectorize(), builder);
this.uvs = new UVs(uvs.getSprite(), vertUv);
}
public void compute() {
}
public Quad[] subdivide(int count) {
List<Quad> rects = Lists.newArrayList();
Pair<Quad, Quad> firstDivide = divide(false);
Pair<Quad, Quad> secondDivide = firstDivide.getLeft().divide(true);
rects.add(secondDivide.getLeft());
if (firstDivide.getRight() != null) {
Pair<Quad, Quad> thirdDivide = firstDivide.getRight().divide(true);
rects.add(thirdDivide.getLeft());
rects.add(thirdDivide.getRight());
} else {
rects.add(null);
rects.add(null);
}
rects.add(secondDivide.getRight());
return rects.toArray(new Quad[rects.size()]);
}
@Nullable
private Pair<Quad, Quad> divide(boolean vertical) {
float min, max;
UVs uvs = getUvs().normalize();
if (vertical) {
min = uvs.minV;
max = uvs.maxV;
} else {
min = uvs.minU;
max = uvs.maxU;
}
if (min < 0.5 && max > 0.5) {
UVs first = new UVs(vertical ? uvs.minU : 0.5f, vertical ? 0.5f : uvs.minV, uvs.maxU, uvs.maxV, uvs.getSprite());
UVs second = new UVs(uvs.minU, uvs.minV, vertical ? uvs.maxU : 0.5f, vertical ? 0.5f : uvs.maxV, uvs.getSprite());
int firstIndex = 0;
for (int i = 0; i < vertUv.length; i++) {
if (vertUv[i].y == getUvs().minV && vertUv[i].x == getUvs().minU) {
firstIndex = i;
break;
}
}
float f = (0.5f - min) / (max - min);
Vector3f[] firstQuad = new Vector3f[4];
Vector3f[] secondQuad = new Vector3f[4];
for (int i = 0; i < 4; i++) {
int idx = (firstIndex + i) % 4;
firstQuad[i] = new Vector3f(vertPos[idx]);
secondQuad[i] = new Vector3f(vertPos[idx]);
}
int i1 = 0;
int i2 = vertical ? 1 : 3;
int j1 = vertical ? 3 : 1;
int j2 = 2;
firstQuad[i1].x = lerp(firstQuad[i1].x, firstQuad[i2].x, f);
firstQuad[i1].y = lerp(firstQuad[i1].y, firstQuad[i2].y, f);
firstQuad[i1].z = lerp(firstQuad[i1].z, firstQuad[i2].z, f);
firstQuad[j1].x = lerp(firstQuad[j1].x, firstQuad[j2].x, f);
firstQuad[j1].y = lerp(firstQuad[j1].y, firstQuad[j2].y, f);
firstQuad[j1].z = lerp(firstQuad[j1].z, firstQuad[j2].z, f);
secondQuad[i2].x = lerp(secondQuad[i1].x, secondQuad[i2].x, f);
secondQuad[i2].y = lerp(secondQuad[i1].y, secondQuad[i2].y, f);
secondQuad[i2].z = lerp(secondQuad[i1].z, secondQuad[i2].z, f);
secondQuad[j2].x = lerp(secondQuad[j1].x, secondQuad[j2].x, f);
secondQuad[j2].y = lerp(secondQuad[j1].y, secondQuad[j2].y, f);
secondQuad[j2].z = lerp(secondQuad[j1].z, secondQuad[j2].z, f);
Quad q1 = new Quad(firstQuad, first.relativize(), builder);
Quad q2 = new Quad(secondQuad, second.relativize(), builder);
return Pair.of(q1, q2);
} else {
return Pair.of(this, null);
}
}
static float lerp(float a, float b, float f) {
float ret = (a * (1 - f)) + (b * f);
return ret;
}
static float normalize(float min, float max, float x) {
float ret = (x - min) / (max - min);
return ret;
}
public Quad rotate(int amount) {
Vector2f[] uvs = new Vector2f[4];
TextureAtlasSprite s = getUvs().getSprite();
for (int i = 0; i < 4; i++) {
Vector2f normalized = new Vector2f(normalize(s.getMinU(), s.getMaxU(), vertUv[i].x), normalize(s.getMinV(), s.getMaxV(), vertUv[i].y));
Vector2f uv;
switch (amount) {
case 1:
uv = new Vector2f(normalized.y, 1 - normalized.x);
break;
case 2:
uv = new Vector2f(1 - normalized.x, 1 - normalized.y);
break;
case 3:
uv = new Vector2f(1 - normalized.y, normalized.x);
break;
default:
uv = new Vector2f(normalized.x, normalized.y);
break;
}
uvs[i] = uv;
}
for (int i = 0; i < uvs.length; i++) {
uvs[i] = new Vector2f(lerp(s.getMinU(), s.getMaxU(), uvs[i].x), lerp(s.getMinV(), s.getMaxV(), uvs[i].y));
}
Quad ret = new Quad(vertPos, uvs, builder);
ret.uvs = new UVs(getUvs().getSprite(), ret.vertUv);
return ret;
}
public Quad derotate() {
int start = 0;
for (int i = 0; i < 4; i++) {
if (vertUv[i].x <= getUvs().minU && vertUv[i].y <= getUvs().minV) {
start = i;
break;
}
}
Vector2f[] uvs = new Vector2f[4];
for (int i = 0; i < 4; i++) {
uvs[i] = vertUv[(i + start) % 4];
}
return new Quad(vertPos, uvs, builder);
}
public BakedQuad rebake() {
UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(this.builder.vertexFormat);
builder.setQuadOrientation(this.builder.quadOrientation);
builder.setQuadTint(this.builder.quadTint);
for (int v = 0; v < 4; v++) {
for (int i = 0; i < this.builder.vertexFormat.getElementCount(); i++) {
VertexFormatElement ele = this.builder.vertexFormat.getElement(i);
switch (ele.getUsage()) {
case UV:
Vector2f uv = vertUv[v];
builder.put(i, uv.x, uv.y, 0, 1);
break;
case POSITION:
Vector3f p = vertPos[v];
builder.put(i, p.x, p.y, p.z, 1);
break;
default:
builder.put(i, this.builder.data.get(ele.getUsage()).get(v));
}
}
}
return builder.build();
}
public Quad transformUVs(TextureAtlasSprite sprite) {
return transformUVs(sprite, CTM.FULL_TEXTURE.normalize());
}
public Quad transformUVs(TextureAtlasSprite sprite, ISubmap submap) {
return new Quad(vertPos, getUvs().transform(sprite, submap), builder);
}
public Quad grow() {
return new Quad(vertPos, getUvs().normalizeQuadrant(), builder);
}
public static Quad from(BakedQuad baked, VertexFormat fmt) {
Builder b = new Builder(fmt);
baked.pipe(b);
return b.build().derotate(); // for now we will ignore rotated UVs
}
@RequiredArgsConstructor
public static class Builder implements IVertexConsumer {
@Getter
private final VertexFormat vertexFormat;
@Setter
private int quadTint;
@Setter
private EnumFacing quadOrientation;
@Override
public void setQuadColored() {}
private ListMultimap<EnumUsage, float[]> data = MultimapBuilder.enumKeys(EnumUsage.class).arrayListValues().build();
@Override
public void put(int element, float... data) {
float[] copy = new float[data.length];
System.arraycopy(data, 0, copy, 0, data.length);
VertexFormatElement ele = vertexFormat.getElement(element);
this.data.put(ele.getUsage(), copy);
}
public Quad build() {
Vector3f[] verts = fromData(data.get(EnumUsage.POSITION), 3);
Vector2f[] uvs = fromData(data.get(EnumUsage.UV), 2);
return new Quad(verts, uvs, this);
}
@SuppressWarnings("unchecked")
private <T extends Vector> T[] fromData(List<float[]> data, int size) {
Vector[] ret = size == 2 ? new Vector2f[data.size()] : new Vector3f[data.size()];
for (int i = 0; i < data.size(); i++) {
ret[i] = size == 2 ? new Vector2f(data.get(i)[0], data.get(i)[1]) : new Vector3f(data.get(i)[0], data.get(i)[1], data.get(i)[2]);
}
return (T[]) ret;
}
}
}
@@ -0,0 +1,94 @@
package mekanism.client.render.ctm;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@Getter
@AllArgsConstructor
public class Submap implements ISubmap {
private final float width, height;
private final float xOffset, yOffset;
private final SubmapNormalized normalized = new SubmapNormalized(this);
@Override
public float getInterpolatedU(TextureAtlasSprite sprite, float u) {
return sprite.getInterpolatedU(getXOffset() + u / getWidth());
}
@Override
public float getInterpolatedV(TextureAtlasSprite sprite, float v) {
return sprite.getInterpolatedV(getYOffset() + v / getWidth());
}
@Override
public float[] toArray() {
return new float[] { getXOffset(), getYOffset(), getXOffset() + getWidth(), getYOffset() + getHeight() };
}
@Override
public SubmapNormalized normalize() {
return normalized;
}
@Override
public ISubmap relativize() {
return this;
}
private static final float FACTOR = 16f;
@RequiredArgsConstructor
private static class SubmapNormalized implements ISubmap {
private final ISubmap parent;
@Override
public float getXOffset() {
return parent.getXOffset() / FACTOR;
}
@Override
public float getYOffset() {
return parent.getYOffset() / FACTOR;
}
@Override
public float getWidth() {
return parent.getWidth() / FACTOR;
}
@Override
public float getHeight() {
return parent.getHeight() / FACTOR;
}
@Override
public ISubmap relativize() {
return parent;
}
@Override
public ISubmap normalize() {
return this;
}
@Override
public float getInterpolatedU(TextureAtlasSprite sprite, float u) {
return parent.getInterpolatedU(sprite, u);
}
@Override
public float getInterpolatedV(TextureAtlasSprite sprite, float v) {
return parent.getInterpolatedV(sprite, v);
}
@Override
public float[] toArray() {
return parent.toArray();
}
}
}
@@ -0,0 +1,24 @@
package mekanism.client.render.ctm;
import lombok.Getter;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.ResourceLocation;
/**
* Callback when textures are stitched
*/
@Getter
public class TextureSpriteCallback {
private ResourceLocation location;
private TextureAtlasSprite sprite;
public TextureSpriteCallback(ResourceLocation loc) {
this.location = loc;
}
public void stitch(TextureMap map) {
this.sprite = map.registerSprite(location);
}
}
@@ -13,15 +13,13 @@ import mekanism.common.tile.TileEntityEnergyCube;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.MekanismUtils.ResourceType;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
public class RenderEnergyCube extends TileEntitySpecialRenderer<TileEntityEnergyCube>
{
@@ -48,7 +46,6 @@ public class RenderEnergyCube extends TileEntitySpecialRenderer<TileEntityEnergy
@Override
public void renderTileEntityAt(TileEntityEnergyCube tileEntity, double x, double y, double z, float partialTick, int destroyStage)
{
GL11.glPushMatrix();
GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 2.5F);
@@ -5,6 +5,7 @@ import java.util.Random;
import mekanism.api.energy.IEnergizedItem;
import mekanism.api.energy.IStrictEnergyStorage;
import mekanism.client.render.ctm.PropertyCTMRenderContext;
import mekanism.common.Mekanism;
import mekanism.common.Tier.BaseTier;
import mekanism.common.base.IActiveState;
@@ -21,20 +22,13 @@ import mekanism.common.multiblock.IMultiblock;
import mekanism.common.multiblock.IStructuralMultiblock;
import mekanism.common.tile.TileEntityBasicBlock;
import mekanism.common.tile.TileEntityBin;
import mekanism.common.tile.TileEntityBoilerCasing;
import mekanism.common.tile.TileEntityBoilerValve;
import mekanism.common.tile.TileEntityDynamicTank;
import mekanism.common.tile.TileEntityInductionCasing;
import mekanism.common.tile.TileEntityInductionCell;
import mekanism.common.tile.TileEntityInductionProvider;
import mekanism.common.tile.TileEntityMultiblock;
import mekanism.common.tile.TileEntityPressureDisperser;
import mekanism.common.tile.TileEntitySecurityDesk;
import mekanism.common.tile.TileEntityStructuralGlass;
import mekanism.common.tile.TileEntitySuperheatingElement;
import mekanism.common.tile.TileEntityThermalEvaporationController;
import mekanism.common.tile.TileEntityThermalEvaporationValve;
import mekanism.common.util.LangUtils;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.SecurityUtils;
import net.minecraft.block.Block;
@@ -52,19 +46,19 @@ import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import buildcraft.api.tools.IToolWrench;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import buildcraft.api.tools.IToolWrench;
/**
* Block class for handling multiple metal block IDs.
@@ -99,10 +93,8 @@ import net.minecraftforge.fml.relauncher.SideOnly;
*/
public abstract class BlockBasic extends Block//TODO? implements IBlockCTM, ICustomBlockIcon
{
// public CTMData[][] ctms = new CTMData[16][4];
public static final PropertyCTMRenderContext ctmProperty = new PropertyCTMRenderContext();
// public static String ICON_BASE = "mekanism:SteelCasing";
public BlockBasic()
{
super(Material.iron);
@@ -14,8 +14,8 @@ import mekanism.common.Mekanism;
import mekanism.common.base.IChunkLoadHandler;
import mekanism.common.base.ITileComponent;
import mekanism.common.base.ITileNetwork;
import mekanism.common.block.states.BlockStateMachine.MachineType;
import mekanism.common.block.states.BlockStateMachine;
import mekanism.common.block.states.BlockStateMachine.MachineType;
import mekanism.common.frequency.Frequency;
import mekanism.common.frequency.FrequencyManager;
import mekanism.common.frequency.IFrequencyHandler;
@@ -37,9 +37,9 @@ import net.minecraftforge.fml.common.Optional.Method;
public abstract class TileEntityBasicBlock extends TileEntity implements IWrenchable, ITileNetwork, IChunkLoadHandler, IFrequencyHandler
{
/** The direction this block is facing. */
public EnumFacing facing;
public EnumFacing facing = EnumFacing.NORTH;
public EnumFacing clientFacing;
public EnumFacing clientFacing = facing;
public HashSet<EntityPlayer> openedThisTick = new HashSet<EntityPlayer>();