file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
GuiSnowstormParticleMorphSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormParticleMorphSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentParticleMorph;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiNestedEdit;
import net.minecraft.client.Minecraft;
public class GuiSnowstormParticleMorphSection extends GuiSnowstormComponentSection<BedrockComponentParticleMorph>
{
public GuiToggleElement enabled;
public GuiToggleElement renderTexture;
public GuiNestedEdit pickMorph;
public GuiSnowstormParticleMorphSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.enabled = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.particle_morph.enabled"), (b) ->
{
this.component.enabled = b.isToggled();
this.parent.dirty();
});
this.renderTexture = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.particle_morph.render_texture"), (b) ->
{
this.component.renderTexture = b.isToggled();
this.parent.dirty();
});
this.pickMorph = new GuiNestedEdit(mc, (editing) ->
{
ClientProxy.panels.addMorphs(this.parent, editing, this.component.morph.get());
this.parent.dirty();
});
this.pickMorph.marginTop(80);
this.fields.add(this.enabled, this.pickMorph, this.renderTexture);
}
public void setMorph(AbstractMorph morph)
{
this.component.morph.set(morph);
this.pickMorph.setMorph(morph);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.particle_morph.title";
}
@Override
public void draw(GuiContext context)
{
if (!this.component.morph.isEmpty())
{
AbstractMorph morph = this.component.morph.get();
int x = this.area.mx();
int y = this.enabled.area.y(1F) + 50;
GuiDraw.scissor(this.area.x, this.area.y, this.area.w, this.area.h, context);
morph.renderOnScreen(this.mc.player, x, y, this.area.h / 3.5F, 1.0F);
GuiDraw.unscissor(context);
}
super.draw(context);
}
@Override
protected BedrockComponentParticleMorph getComponent(BedrockScheme scheme)
{
return this.scheme.getOrCreate(BedrockComponentParticleMorph.class);
}
@Override
protected void fillData()
{
this.enabled.toggled(this.component.enabled);
this.renderTexture.toggled(this.component.renderTexture);
this.pickMorph.setMorph(this.component.morph.get());
}
}
| 3,119 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSectionManager;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.mclib.McLib;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.ColorUtils;
import net.minecraft.client.Minecraft;
public abstract class GuiSnowstormSection extends GuiElement
{
public GuiLabel title;
public GuiElement fields;
protected BedrockScheme scheme;
protected GuiSnowstorm parent;
public GuiSnowstormSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc);
this.parent = parent;
this.title = Elements.label(IKey.lang(this.getTitle())).background(() -> ColorUtils.HALF_BLACK + McLib.primaryColor.get());
this.fields = new GuiElement(mc);
this.fields.flex().column(5).stretch().vertical().height(20);
this.flex().column(5).stretch().vertical();
this.add(this.title);
this.collapseState();
}
protected void collapseState()
{
if (!GuiSectionManager.isCollapsed(this.getClass().getSimpleName()))
{
this.add(this.fields);
}
}
protected void resizeParent()
{
this.getParent().resize();
}
public void dirty()
{
this.parent.dirty();
}
public abstract String getTitle();
public MolangExpression parse(String string, GuiTextElement element, MolangExpression old)
{
if (string.isEmpty())
{
return MolangParser.ZERO;
}
try
{
MolangExpression expression = this.scheme.parser.parseExpression(string);
element.field.setTextColor(0xffffff);
this.parent.dirty();
return expression;
}
catch (Exception e)
{}
element.field.setTextColor(0xff2244);
return old;
}
public void set(GuiTextElement element, MolangExpression expression)
{
element.field.setTextColor(0xffffff);
element.setText(expression.toString());
}
public void setScheme(BedrockScheme scheme)
{
this.scheme = scheme;
}
public void beforeSave(BedrockScheme scheme)
{}
/**
* Toggle visibility of the field section
*/
@Override
public boolean mouseClicked(GuiContext context)
{
if (super.mouseClicked(context))
{
return true;
}
if (this.title.area.isInside(context))
{
if (this.fields.hasParent())
{
this.fields.removeFromParent();
GuiSectionManager.setCollapsed(this.getClass().getSimpleName(), true);
}
else
{
this.add(this.fields);
GuiSectionManager.setCollapsed(this.getClass().getSimpleName(), false);
}
this.resizeParent();
return true;
}
return false;
}
} | 3,573 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormMotionSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormMotionSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentInitialSpeed;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentInitialSpin;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotion;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotionDynamic;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotionParametric;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiSnowstormMotionSection extends GuiSnowstormModeSection<BedrockComponentMotion>
{
public GuiElement position;
public GuiElement positionElements;
public GuiTextElement positionSpeed;
public GuiTextElement positionX;
public GuiTextElement positionY;
public GuiTextElement positionZ;
public GuiTextElement positionDrag;
public GuiElement positionDragRow;
public GuiElement positionTitle = Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_title")).marginTop(12);
public GuiElement rotation;
public GuiTextElement rotationAngle;
public GuiTextElement rotationRate;
public GuiTextElement rotationAcceleration;
public GuiElement rotationDragRow;
public GuiTextElement rotationDrag;
private BedrockComponentInitialSpeed speed;
private BedrockComponentInitialSpin spin;
public GuiSnowstormMotionSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.positionSpeed = new GuiTextElement(mc, 10000, (str) -> this.speed.speed = this.parse(str, this.positionSpeed, this.speed.speed));
this.positionSpeed.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.position_speed"));
this.positionX = new GuiTextElement(mc, 10000, (str) -> this.updatePosition(str, this.positionX, 0));
this.positionX.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_x"));
this.positionY = new GuiTextElement(mc, 10000, (str) -> this.updatePosition(str, this.positionY, 1));
this.positionY.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_y"));
this.positionZ = new GuiTextElement(mc, 10000, (str) -> this.updatePosition(str, this.positionZ, 2));
this.positionZ.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_z"));
this.positionDrag = new GuiTextElement(mc, 10000, (str) ->
{
BedrockComponentMotionDynamic component = (BedrockComponentMotionDynamic) this.component;
component.motionDrag = this.parse(str, this.positionDrag, component.motionDrag);
});
this.positionDrag.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.position_drag"));
this.rotationAngle = new GuiTextElement(mc, 10000, (str) -> this.spin.rotation = this.parse(str, this.rotationAngle, this.spin.rotation));
this.rotationAngle.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.rotation_angle"));
this.rotationRate = new GuiTextElement(mc, 10000, (str) -> this.spin.rate = this.parse(str, this.rotationRate, this.spin.rate));
this.rotationRate.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.rotation_speed"));
this.rotationAcceleration = new GuiTextElement(mc, 10000, (str) ->
{
if (this.component instanceof BedrockComponentMotionDynamic)
{
BedrockComponentMotionDynamic component = (BedrockComponentMotionDynamic) this.component;
component.rotationAcceleration = this.parse(str, this.rotationAcceleration, component.rotationAcceleration);
}
else
{
BedrockComponentMotionParametric component = (BedrockComponentMotionParametric) this.component;
component.rotation = this.parse(str, this.rotationAcceleration, component.rotation);
}
});
this.rotationAcceleration.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.rotation_acceleration"));
this.rotationDrag = new GuiTextElement(mc, 10000, (str) ->
{
BedrockComponentMotionDynamic component = (BedrockComponentMotionDynamic) this.component;
component.rotationDrag = this.parse(str, this.rotationDrag, component.rotationDrag);
});
this.rotationDrag.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.rotation_drag"));
this.position = new GuiElement(mc);
this.position.flex().column(5).vertical().stretch();
this.position.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.speed")).marginTop(12), this.positionSpeed);
this.positionElements = new GuiElement(mc);
this.positionElements.flex().column(5).vertical().stretch();
this.positionElements.add(this.positionX, this.positionY, this.positionZ);
this.positionElements.addBefore(this.positionX, this.positionTitle);
this.position.add(this.positionElements);
this.positionDragRow = new GuiElement(mc);
this.rotationDragRow = new GuiElement(mc);
this.rotationDragRow.flex().column(5).vertical().stretch();
this.rotationDragRow.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.rotation_drag")), this.rotationDrag);
this.positionDragRow.flex().column(5).vertical().stretch();
this.positionDragRow.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.position_drag_title")), this.positionDrag);
this.rotation = new GuiElement(mc);
this.rotation.flex().column(5).vertical().stretch();
this.rotation.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.rotation")).marginTop(12), this.rotationAngle, this.rotationRate);
this.rotation.add(this.rotationAcceleration);
this.fields.add(this.position, this.rotation);
}
private void updatePosition(String str, GuiTextElement element, int index)
{
if (this.component instanceof BedrockComponentMotionDynamic)
{
BedrockComponentMotionDynamic component = (BedrockComponentMotionDynamic) this.component;
component.motionAcceleration[index] = this.parse(str, element, component.motionAcceleration[index]);
}
else
{
BedrockComponentMotionParametric component = (BedrockComponentMotionParametric) this.component;
component.position[index] = this.parse(str, element, component.position[index]);
}
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.motion.title";
}
@Override
protected void fillModes(GuiCirculateElement button)
{
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.motion.dynamic"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.motion.parametric"));
}
@Override
protected Class<BedrockComponentMotion> getBaseClass()
{
return BedrockComponentMotion.class;
}
@Override
protected Class getDefaultClass()
{
return BedrockComponentMotionDynamic.class;
}
@Override
protected Class getModeClass(int value)
{
if (value == 1)
{
return BedrockComponentMotionParametric.class;
}
return BedrockComponentMotionDynamic.class;
}
@Override
protected void fillData()
{
super.fillData();
this.speed = this.scheme.getOrCreate(BedrockComponentInitialSpeed.class);
this.spin = this.scheme.getOrCreate(BedrockComponentInitialSpin.class);
this.set(this.positionSpeed, this.speed.speed);
this.set(this.rotationAngle, this.spin.rotation);
this.set(this.rotationRate, this.spin.rate);
this.positionDragRow.removeFromParent();
this.rotationDragRow.removeFromParent();
if (this.component instanceof BedrockComponentMotionDynamic)
{
BedrockComponentMotionDynamic component = (BedrockComponentMotionDynamic) this.component;
this.positionElements.remove(this.positionTitle);
this.positionTitle = Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_title")).marginTop(12);
this.positionElements.addBefore(this.positionX, this.positionTitle);
this.positionX.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_x"));
this.positionY.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_y"));
this.positionZ.tooltip(IKey.lang("blockbuster.gui.snowstorm.motion.acceleration_z"));
this.set(this.positionX, component.motionAcceleration[0]);
this.set(this.positionY, component.motionAcceleration[1]);
this.set(this.positionZ, component.motionAcceleration[2]);
this.set(this.rotationAcceleration, component.rotationAcceleration);
this.set(this.positionDrag, component.motionDrag);
this.set(this.rotationDrag, component.rotationDrag);
this.position.add(this.positionDragRow);
this.rotation.add(this.rotationDragRow);
}
else
{
BedrockComponentMotionParametric component = (BedrockComponentMotionParametric) this.component;
this.positionElements.remove(this.positionTitle);
this.positionTitle = Elements.label(IKey.lang("blockbuster.gui.snowstorm.motion.position"));
this.positionTitle.marginTop(12);
this.positionElements.addBefore(this.positionX, this.positionTitle);
this.positionX.tooltip(IKey.lang("blockbuster.gui.model_block.x"));
this.positionY.tooltip(IKey.lang("blockbuster.gui.model_block.y"));
this.positionZ.tooltip(IKey.lang("blockbuster.gui.model_block.z"));
this.set(this.positionX, component.position[0]);
this.set(this.positionY, component.position[1]);
this.set(this.positionZ, component.position[2]);
this.set(this.rotationAcceleration, component.rotation);
}
this.resizeParent();
}
} | 10,532 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormShapeSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormShapeSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSectionManager;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeBase;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeBox;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeDisc;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeEntityAABB;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapePoint;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeSphere;
import mchorse.blockbuster.client.particles.components.shape.ShapeDirection;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.molang.MolangParser;
import net.minecraft.client.Minecraft;
public class GuiSnowstormShapeSection extends GuiSnowstormModeSection<BedrockComponentShapeBase>
{
public GuiTextElement offsetX;
public GuiTextElement offsetY;
public GuiTextElement offsetZ;
public GuiDirectionSection direction;
public GuiToggleElement surface;
public GuiLabel radiusLabel;
public GuiTextElement radius;
public GuiLabel label;
public GuiTextElement x;
public GuiTextElement y;
public GuiTextElement z;
public GuiSnowstormShapeSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.offsetX = new GuiTextElement(mc, 10000, (str) -> this.component.offset[0] = this.parse(str, this.offsetX, this.component.offset[0]));
this.offsetX.tooltip(IKey.lang("blockbuster.gui.model_block.x"));
this.offsetY = new GuiTextElement(mc, 10000, (str) -> this.component.offset[1] = this.parse(str, this.offsetY, this.component.offset[1]));
this.offsetY.tooltip(IKey.lang("blockbuster.gui.model_block.y"));
this.offsetZ = new GuiTextElement(mc, 10000, (str) -> this.component.offset[2] = this.parse(str, this.offsetZ, this.component.offset[2]));
this.offsetZ.tooltip(IKey.lang("blockbuster.gui.model_block.z"));
this.direction = new GuiDirectionSection(mc, this);
this.surface = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.shape.surface"), (b) ->
{
this.component.surface = b.isToggled();
this.parent.dirty();
});
this.surface.tooltip(IKey.lang("blockbuster.gui.snowstorm.shape.surface_tooltip"));
this.radiusLabel = Elements.label(IKey.lang("blockbuster.gui.snowstorm.shape.radius"));
this.radiusLabel.marginTop(12);
this.radius = new GuiTextElement(mc, 10000, (str) ->
{
BedrockComponentShapeSphere sphere = (BedrockComponentShapeSphere) this.component;
sphere.radius = this.parse(str, this.radius, sphere.radius);
});
this.label = Elements.label(IKey.lang(""));
this.label.marginTop(12);
this.x = new GuiTextElement(mc, 10000, (str) -> this.updateNormalDimension(str, this.x, 0));
this.x.tooltip(IKey.lang("blockbuster.gui.model_block.x"));
this.y = new GuiTextElement(mc, 10000, (str) -> this.updateNormalDimension(str, this.y, 1));
this.y.tooltip(IKey.lang("blockbuster.gui.model_block.y"));
this.z = new GuiTextElement(mc, 10000, (str) -> this.updateNormalDimension(str, this.z, 2));
this.z.tooltip(IKey.lang("blockbuster.gui.model_block.z"));
this.modeLabel.label.set("blockbuster.gui.snowstorm.shape.shape");
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.shape.offset")).marginTop(12), this.offsetX, this.offsetY, this.offsetZ, this.direction, this.surface);
}
@Override
protected void collapseState()
{
GuiSectionManager.setDefaultState(this.getClass().getSimpleName(), false);
super.collapseState();
}
private void updateNormalDimension(String str, GuiTextElement element, int index)
{
if (this.component instanceof BedrockComponentShapeBox)
{
BedrockComponentShapeBox box = (BedrockComponentShapeBox) this.component;
box.halfDimensions[index] = this.parse(str, element, box.halfDimensions[index]);
}
else if (this.component instanceof BedrockComponentShapeDisc)
{
BedrockComponentShapeDisc disc = (BedrockComponentShapeDisc) this.component;
disc.normal[index] = this.parse(str, element, disc.normal[index]);
}
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.shape.title";
}
@Override
protected void fillModes(GuiCirculateElement button)
{
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.point"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.box"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.sphere"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.disc"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.aabb"));
}
@Override
protected void restoreInfo(BedrockComponentShapeBase component, BedrockComponentShapeBase old)
{
component.offset = old.offset;
component.direction = old.direction;
component.surface = old.surface;
if (component instanceof BedrockComponentShapeSphere && old instanceof BedrockComponentShapeSphere)
{
((BedrockComponentShapeSphere) component).radius = ((BedrockComponentShapeSphere) old).radius;
}
}
@Override
protected Class<BedrockComponentShapeBase> getBaseClass()
{
return BedrockComponentShapeBase.class;
}
@Override
protected Class getDefaultClass()
{
return BedrockComponentShapePoint.class;
}
@Override
protected Class getModeClass(int value)
{
if (value == 1)
{
return BedrockComponentShapeBox.class;
}
else if (value == 2)
{
return BedrockComponentShapeSphere.class;
}
else if (value == 3)
{
return BedrockComponentShapeDisc.class;
}
else if (value == 4)
{
return BedrockComponentShapeEntityAABB.class;
}
return BedrockComponentShapePoint.class;
}
@Override
protected void fillData()
{
super.fillData();
this.set(this.offsetX, this.component.offset[0]);
this.set(this.offsetY, this.component.offset[1]);
this.set(this.offsetZ, this.component.offset[2]);
this.direction.fillData();
this.surface.toggled(this.component.surface);
if (this.component instanceof BedrockComponentShapeSphere)
{
this.set(this.radius, ((BedrockComponentShapeSphere) this.component).radius);
}
this.setNormalDimension(this.x, 0);
this.setNormalDimension(this.y, 1);
this.setNormalDimension(this.z, 2);
this.radiusLabel.removeFromParent();;
this.radius.removeFromParent();
this.label.removeFromParent();
this.x.removeFromParent();
this.y.removeFromParent();
this.z.removeFromParent();
this.surface.removeFromParent();
if (this.component instanceof BedrockComponentShapeSphere)
{
this.fields.add(this.radiusLabel, this.radius);
}
if (this.component instanceof BedrockComponentShapeBox || this.component instanceof BedrockComponentShapeDisc)
{
this.label.label.set("blockbuster.gui.snowstorm.shape." + (this.component instanceof BedrockComponentShapeBox ? "box_size" : "normal"));
this.fields.add(this.label);
this.fields.add(this.x);
this.fields.add(this.y);
this.fields.add(this.z);
}
this.fields.add(this.surface);
this.resizeParent();
}
private void setNormalDimension(GuiTextElement text, int index)
{
if (this.component instanceof BedrockComponentShapeBox)
{
this.set(text, ((BedrockComponentShapeBox) this.component).halfDimensions[index]);
}
else if (this.component instanceof BedrockComponentShapeDisc)
{
this.set(text, ((BedrockComponentShapeDisc) this.component).normal[index]);
}
}
public static class GuiDirectionSection extends GuiElement
{
public GuiSnowstormShapeSection parent;
public GuiCirculateElement mode;
public GuiTextElement x;
public GuiTextElement y;
public GuiTextElement z;
public GuiDirectionSection(Minecraft mc, GuiSnowstormShapeSection parent)
{
super(mc);
this.parent = parent;
this.mode = new GuiCirculateElement(mc, (b) ->
{
int value = this.mode.getValue();
if (value == 0)
{
this.parent.component.direction = ShapeDirection.OUTWARDS;
}
else if (value == 1)
{
this.parent.component.direction = ShapeDirection.INWARDS;
}
else
{
this.parent.component.direction = new ShapeDirection.Vector(MolangParser.ZERO, MolangParser.ZERO, MolangParser.ZERO);
}
this.parent.parent.dirty();
this.fillData();
});
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.direction_outwards"));
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.direction_inwards"));
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.shape.direction_vector"));
this.x = new GuiTextElement(mc, 10000, (str) -> this.getVector().x = this.parent.parse(str, this.x, this.getVector().x));
this.x.tooltip(IKey.lang("blockbuster.gui.model_block.x"));
this.y = new GuiTextElement(mc, 10000, (str) -> this.getVector().y = this.parent.parse(str, this.y, this.getVector().y));
this.y.tooltip(IKey.lang("blockbuster.gui.model_block.y"));
this.z = new GuiTextElement(mc, 10000, (str) -> this.getVector().z = this.parent.parse(str, this.z, this.getVector().z));
this.z.tooltip(IKey.lang("blockbuster.gui.model_block.z"));
this.flex().column(5).vertical().stretch().height(20);
this.add(Elements.row(mc, 5, 0, 20, Elements.label(IKey.lang("blockbuster.gui.snowstorm.shape.direction"), 20).anchor(0, 0.5F), this.mode));
}
private ShapeDirection.Vector getVector()
{
return (ShapeDirection.Vector) this.parent.component.direction;
}
public void fillData()
{
boolean isVector = this.parent.component.direction instanceof ShapeDirection.Vector;
int value = 0;
if (this.parent.component.direction == ShapeDirection.INWARDS)
{
value = 1;
}
else if (isVector)
{
value = 2;
}
this.mode.setValue(value);
this.x.removeFromParent();
this.y.removeFromParent();
this.z.removeFromParent();
if (isVector)
{
ShapeDirection.Vector vector = (ShapeDirection.Vector) this.parent.component.direction;
this.parent.set(this.x, vector.x);
this.parent.set(this.y, vector.y);
this.parent.set(this.z, vector.z);
this.add(this.x, this.y, this.z);
}
this.parent.resizeParent();
}
}
}
| 12,298 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormModeSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormModeSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public abstract class GuiSnowstormModeSection <T extends BedrockComponentBase> extends GuiSnowstormComponentSection<T>
{
public GuiCirculateElement mode;
public GuiLabel modeLabel;
public GuiSnowstormModeSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.mode = new GuiCirculateElement(mc, (b) -> this.updateMode(this.mode.getValue()));
this.fillModes(this.mode);
this.modeLabel = Elements.label(IKey.lang("blockbuster.gui.snowstorm.mode"), 20).anchor(0, 0.5F);
this.fields.add(Elements.row(mc, 5, 0, 20, this.modeLabel, this.mode));
}
@Override
protected T getComponent(BedrockScheme scheme)
{
return scheme.getOrCreate(this.getBaseClass(), this.getDefaultClass());
}
@Override
protected void fillData()
{
super.fillData();
for (int i = 0, c = this.mode.getLabels().size(); i < c; i ++)
{
if (this.getModeClass(i) == this.component.getClass())
{
this.mode.setValue(i);
break;
}
}
}
protected abstract void fillModes(GuiCirculateElement button);
protected void updateMode(int value)
{
T old = this.component;
this.component = this.scheme.replace(this.getBaseClass(), this.getModeClass(this.mode.getValue()));
this.restoreInfo(this.component, old);
this.parent.dirty();
this.fillData();
}
protected void restoreInfo(T component, T old)
{}
protected abstract Class<T> getBaseClass();
protected abstract Class getDefaultClass();
protected abstract Class getModeClass(int value);
} | 2,262 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormRateSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormRateSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSectionManager;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.components.rate.BedrockComponentRate;
import mchorse.blockbuster.client.particles.components.rate.BedrockComponentRateInstant;
import mchorse.blockbuster.client.particles.components.rate.BedrockComponentRateSteady;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.tooltips.LabelTooltip;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiSnowstormRateSection extends GuiSnowstormModeSection<BedrockComponentRate>
{
public GuiTextElement rate;
public GuiTextElement particles;
public GuiSnowstormRateSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.rate = new GuiTextElement(mc, 10000, (str) ->
{
BedrockComponentRateSteady comp = (BedrockComponentRateSteady) this.component;
comp.spawnRate = this.parse(str, this.rate, comp.spawnRate);
});
this.rate.tooltip(IKey.lang("blockbuster.gui.snowstorm.rate.spawn_rate"));
this.particles = new GuiTextElement(mc, 10000, (str) -> this.component.particles = this.parse(str, this.particles, this.component.particles));
this.particles.tooltip(IKey.lang(""));
this.fields.add(this.particles);
}
@Override
protected void collapseState()
{
GuiSectionManager.setDefaultState(this.getClass().getSimpleName(), false);
super.collapseState();
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.rate.title";
}
@Override
protected void fillModes(GuiCirculateElement button)
{
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.rate.instant"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.rate.steady"));
}
@Override
protected void restoreInfo(BedrockComponentRate component, BedrockComponentRate old)
{
component.particles = old.particles;
}
@Override
protected Class<BedrockComponentRate> getBaseClass()
{
return BedrockComponentRate.class;
}
@Override
protected Class getDefaultClass()
{
return BedrockComponentRateInstant.class;
}
@Override
protected Class getModeClass(int value)
{
return value == 0 ? BedrockComponentRateInstant.class : BedrockComponentRateSteady.class;
}
@Override
protected void fillData()
{
super.fillData();
this.updateVisibility();
this.set(this.particles, this.component.particles);
((LabelTooltip) this.particles.tooltip).label.set(this.isInstant() ? "blockbuster.gui.snowstorm.rate.particles" : "blockbuster.gui.snowstorm.rate.max_particles");
if (this.component instanceof BedrockComponentRateSteady)
{
this.set(this.rate, ((BedrockComponentRateSteady) this.component).spawnRate );
}
}
private void updateVisibility()
{
if (this.isInstant())
{
this.rate.removeFromParent();
}
else if (!this.rate.hasParent())
{
this.fields.add(this.rate);
}
this.resizeParent();
}
private boolean isInstant()
{
return this.component instanceof BedrockComponentRateInstant;
}
}
| 3,674 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiGradientEditor.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/utils/GuiGradientEditor.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.utils;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormSection;
import mchorse.blockbuster.client.particles.components.appearance.Tint;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.context.GuiContextMenu;
import mchorse.mclib.client.gui.framework.elements.context.GuiSimpleContextMenu;
import mchorse.mclib.client.gui.framework.elements.input.GuiColorElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.Area;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.molang.expressions.MolangValue;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.MathUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
public class GuiGradientEditor extends GuiElement
{
private GuiSnowstormSection section;
private GuiColorElement color;
private Tint.Gradient gradient;
private Tint.Gradient.ColorStop current;
private int dragging = -1;
private int lastX;
private Area a = new Area();
private Area b = new Area();
private Color c = new Color();
public GuiGradientEditor(Minecraft mc, GuiSnowstormSection section, GuiColorElement color)
{
super(mc);
this.section = section;
this.color = color;
this.flex().h(20);
}
private Color fillColor(Tint.Solid solid)
{
this.c.r = (float) solid.r.get();
this.c.g = (float) solid.g.get();
this.c.b = (float) solid.b.get();
this.c.a = (float) solid.a.get();
return this.c;
}
private Area fillBound(Tint.Gradient.ColorStop stop)
{
int x = this.a.x(stop.stop);
this.b.set(x - 3, this.a.ey() - 7, 6, 10);
return this.b;
}
private void fillStop(Tint.Gradient.ColorStop stop)
{
this.current = stop;
this.color.picker.setColor(this.fillColor(stop.color).getRGBAColor());
}
public void setColor(int color)
{
this.c.set(color, true);
((MolangValue) this.current.color.r).value.set(this.c.r);
((MolangValue) this.current.color.g).value.set(this.c.g);
((MolangValue) this.current.color.b).value.set(this.c.b);
((MolangValue) this.current.color.a).value.set(this.c.a);
this.section.dirty();
}
public void setGradient(Tint.Gradient gradient)
{
this.gradient = gradient;
if (this.gradient.stops.isEmpty())
{
this.gradient.stops.add(new Tint.Gradient.ColorStop(0, new Tint.Solid()));
}
this.fillStop(this.gradient.stops.get(0));
this.color.picker.setColor(this.fillColor(this.current.color).getRGBAColor());
}
@Override
public GuiContextMenu createContextMenu(GuiContext context)
{
GuiSimpleContextMenu menu = new GuiSimpleContextMenu(context.mc);
menu.action(Icons.ADD, IKey.lang("blockbuster.gui.snowstorm.lighting.context.add_stop"), () -> this.addColorStop(context.mouseX));
if (this.gradient.stops.size() > 1)
{
menu.action(Icons.REMOVE, IKey.lang("blockbuster.gui.snowstorm.lighting.context.remove_stop"), this::removeColorStop);
}
return menu;
}
private void addColorStop(int mouseX)
{
float x = (mouseX - this.area.x) / (float) this.area.w;
Tint.Solid color = new Tint.Solid();
Tint.Gradient.ColorStop stop = new Tint.Gradient.ColorStop(x, color);
color.r = new MolangValue(null, new Constant(1F));
color.g = new MolangValue(null, new Constant(1F));
color.b = new MolangValue(null, new Constant(1F));
color.a = new MolangValue(null, new Constant(1F));
this.gradient.stops.add(stop);
this.gradient.sort();
this.section.dirty();
this.fillStop(stop);
}
private void removeColorStop()
{
if (this.gradient.stops.size() > 2)
{
int index = this.gradient.stops.indexOf(this.current);
this.gradient.stops.remove(index);
index = MathUtils.clamp(index, 0, this.gradient.stops.size() - 1);
this.section.dirty();
this.fillStop(this.gradient.stops.get(index));
}
}
@Override
public void resize()
{
super.resize();
this.a.copy(this.area);
this.a.offset(-1);
}
@Override
public boolean mouseClicked(GuiContext context)
{
if (super.mouseClicked(context))
{
return true;
}
if (this.area.isInside(context))
{
for (Tint.Gradient.ColorStop stop : this.gradient.stops)
{
Area area = this.fillBound(stop);
if (area.isInside(context))
{
this.dragging = 0;
this.lastX = context.mouseX;
this.fillStop(stop);
return true;
}
}
return true;
}
return false;
}
@Override
public void mouseReleased(GuiContext context)
{
super.mouseReleased(context);
if (this.dragging != -1)
{
this.section.dirty();
}
this.dragging = -1;
}
@Override
public void draw(GuiContext context)
{
if (this.dragging == 0 && Math.abs(context.mouseX - this.lastX) > 3)
{
this.dragging = 1;
}
else if (this.dragging == 1)
{
float x = (context.mouseX - this.area.x) / (float) this.area.w;
this.current.stop = MathUtils.clamp(x, 0, 1);
this.gradient.sort();
}
this.area.draw(0xff000000);
int size = this.gradient.stops.size();
GlStateManager.color(1, 1, 1, 1);
Icons.CHECKBOARD.renderArea(this.a.x, this.a.y, this.a.w, this.a.h);
Tint.Gradient.ColorStop first = this.gradient.stops.get(0);
if (first.stop > 0)
{
int x1 = this.a.x(first.stop);
int rgba1 = this.fillColor(first.color).getRGBAColor();
Gui.drawRect(this.a.x, this.a.y, x1, this.a.ey(), rgba1);
}
for (int i = 0; i < size; i++)
{
Tint.Gradient.ColorStop stop = this.gradient.stops.get(i);
Tint.Gradient.ColorStop next = i + 1 < size ? this.gradient.stops.get(i + 1) : stop;
int x1 = this.a.x(stop.stop);
int x2 = this.a.x((next == stop ? 1 : next.stop));
int rgba1 = this.fillColor(stop.color).getRGBAColor();
int rgba2 = this.fillColor(next.color).getRGBAColor();
GuiDraw.drawHorizontalGradientRect(x1, this.a.y, x2, this.a.ey(), rgba1, rgba2);
}
for (int i = 0; i < size; i++)
{
Tint.Gradient.ColorStop stop = this.gradient.stops.get(i);
Area area = this.fillBound(stop);
int x = this.a.x(stop.stop);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), this.current == stop ? 0xffffffff : 0xff000000);
Gui.drawRect(area.x + 1, area.y + 1, area.ex() - 1, area.ey() - 1, this.fillColor(stop.color).getRGBAColor());
}
super.draw(context);
}
} | 7,611 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelEditorPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/GuiModelEditorPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.CommonProxy;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs.GuiModelLimbs;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs.GuiModelList;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs.GuiModelOptions;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs.GuiModelPoses;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiBBModelRenderer;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.ModelUtils;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.parsing.ModelExtrudedLayer;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiPoseTransformations;
import mchorse.blockbuster.utils.mclib.BBIcons;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTexturePicker;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.DummyEntity;
import mchorse.mclib.utils.files.entries.AbstractEntry;
import mchorse.mclib.utils.files.entries.FolderEntry;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.FileUtils;
import org.lwjgl.input.Keyboard;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
public class GuiModelEditorPanel extends GuiBlockbusterPanel
{
/* GUI stuff */
public GuiBBModelRenderer modelRenderer;
private GuiElement icons;
private GuiIconElement openModels;
private GuiIconElement openOptions;
private GuiIconElement openPoses;
private GuiIconElement saveModel;
private GuiIconElement swipe;
private GuiIconElement running;
private GuiIconElement items;
private GuiIconElement hitbox;
private GuiIconElement looking;
private GuiIconElement skin;
private GuiPoseTransformations poseEditor;
private GuiModelLimbs limbs;
private GuiModelPoses poses;
private GuiModelList models;
private GuiModelOptions options;
private GuiTexturePicker picker;
/* Current data */
public String modelName;
public Model model;
public ModelPose pose;
public ModelTransform transform;
public ModelLimb limb;
public IModelLazyLoader modelEntry;
public ModelCustom renderModel;
private boolean dirty;
private boolean held;
public GuiModelEditorPanel(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
this.modelRenderer = new GuiBBModelRenderer(mc);
this.modelRenderer.picker(this::setLimb);
this.modelRenderer.flex().relative(this).wh(1F, 1F);
this.modelRenderer.origin = this.modelRenderer.items = true;
this.picker = new GuiTexturePicker(mc, null);
this.picker.flex().relative(this).wh(1F, 1F);
this.poseEditor = new GuiModelPoseTransformations(mc, this);
this.poseEditor.flex().relative(this).set(0, 0, 256, 70).x(0.5F, -128).y(1, -80);
this.limbs = new GuiModelLimbs(mc, this);
this.limbs.flex().relative(this).x(1F).w(200).h(1F).anchorX(1F);
this.poses = new GuiModelPoses(mc, this);
this.poses.flex().relative(this).y(20).w(140).h(1F, -20);
this.poses.setVisible(false);
this.models = new GuiModelList(mc, this);
this.models.flex().relative(this).y(20).w(140).h(1F, -20);
this.models.setVisible(false);
this.options = new GuiModelOptions(mc, this);
this.options.flex().relative(this).y(20).w(200).h(1F, -20);
this.options.setVisible(false);
/* Toolbar buttons */
this.openModels = new GuiIconElement(mc, Icons.MORE, (b) -> this.toggle(this.models));
this.openOptions = new GuiIconElement(mc, Icons.GEAR, (b) -> this.toggle(this.options));
this.openPoses = new GuiIconElement(mc, Icons.POSE, (b) -> this.toggle(this.poses));
this.saveModel = new GuiIconElement(mc, Icons.SAVED, (b) -> this.saveModel());
this.saveModel.tooltip(IKey.lang("blockbuster.gui.me.tooltips.save"));
this.swipe = new GuiIconElement(mc, BBIcons.ARM1, (b) -> this.modelRenderer.swipe());
this.swipe.tooltip(IKey.lang("blockbuster.gui.me.tooltips.swipe"));
this.swipe.hovered(BBIcons.ARM2);
this.running = new GuiIconElement(mc, BBIcons.LEGS1, (b) -> this.modelRenderer.swinging = !this.modelRenderer.swinging);
this.running.hovered(BBIcons.LEGS2).hoverColor(0xffffffff).tooltip(IKey.lang("blockbuster.gui.me.tooltips.running"));
this.items = new GuiIconElement(mc, BBIcons.NO_ITEMS, (b) ->
{
this.held = !this.held;
((DummyEntity) this.modelRenderer.getEntity()).toggleItems(this.held);
});
this.items.hovered(BBIcons.HELD_ITEMS).tooltip(IKey.lang("blockbuster.gui.me.tooltips.held_items"));
this.hitbox = new GuiIconElement(mc, BBIcons.HITBOX, (b) -> this.modelRenderer.aabb = !this.modelRenderer.aabb);
this.hitbox.tooltip(IKey.lang("blockbuster.gui.me.tooltips.hitbox"));
this.looking = new GuiIconElement(mc, BBIcons.LOOKING, (b) -> this.modelRenderer.looking = !this.modelRenderer.looking);
this.looking.tooltip(IKey.lang("blockbuster.gui.me.tooltips.looking"));
this.skin = new GuiIconElement(mc, Icons.MATERIAL, (b) -> this.pickTexture(this.modelRenderer.texture, (rl) -> this.modelRenderer.texture = rl));
this.skin.tooltip(IKey.lang("blockbuster.gui.me.tooltips.skin"));
this.icons = new GuiElement(mc);
this.icons.flex().relative(this).h(20).row(0).resize().height(20);
this.icons.add(this.openModels, this.openOptions, this.openPoses, this.saveModel);
GuiElement icons = new GuiElement(mc);
icons.flex().relative(this.icons).x(1F, 20).h(20).row(0).resize().height(20);
icons.add(this.swipe, this.running, this.items, this.hitbox, this.looking, this.skin);
this.add(this.modelRenderer, this.poses, this.poseEditor, this.limbs, this.models, this.options, this.icons, icons);
this.keys()
.register(IKey.lang("blockbuster.gui.me.keys.save"), Keyboard.KEY_S, () -> this.saveModel.clickItself(GuiBase.getCurrent()))
.held(Keyboard.KEY_LCONTROL).category(IKey.lang("blockbuster.gui.me.keys.category"));
this.setModel("steve");
}
private void toggle(GuiElement element)
{
boolean visible = element.isVisible();
this.models.setVisible(false);
this.poses.setVisible(false);
this.options.setVisible(false);
element.setVisible(!visible);
}
public void dirty()
{
this.dirty(true);
}
public void dirty(boolean dirty)
{
this.dirty = dirty;
this.updateSaveButton();
}
private void updateSaveButton()
{
this.saveModel.both(this.dirty ? Icons.SAVE : Icons.SAVED);
}
@Override
public void open()
{
this.models.updateModelList();
}
public void pickTexture(ResourceLocation location, Consumer<ResourceLocation> callback)
{
this.picker.fill(location);
this.picker.callback = callback;
this.picker.resize();
this.add(this.picker);
}
public void setLimb(String str)
{
ModelLimb limb = this.model.limbs.get(str);
if (limb != null)
{
this.limb = limb;
if (this.pose != null)
{
this.transform = this.pose.limbs.get(str);
}
this.modelRenderer.limb = limb;
this.poseEditor.set(this.transform);
this.limbs.fillLimbData(limb);
this.limbs.setCurrent(str);
}
}
public void setPose(String str)
{
this.setPose(str, false);
}
public void setPose(String str, boolean scroll)
{
ModelPose pose = this.model.poses.get(str);
if (pose != null)
{
this.pose = pose;
this.modelRenderer.setPose(pose);
this.renderModel.pose = pose;
if (this.limb != null)
{
this.transform = pose.limbs.get(this.limb.name);
}
this.poses.setCurrent(str, scroll);
this.poses.fillPoseData();
this.poseEditor.set(this.transform);
}
}
public void saveModel()
{
this.saveModel(this.modelName);
}
/**
* Save model
*
* This method is responsible for saving model into users's config folder.
*/
public boolean saveModel(String name)
{
if (name.isEmpty())
{
return false;
}
File folder = new File(CommonProxy.configFile, "models/" + name);
File file = new File(folder, "model.json");
String output = ModelUtils.toJson(this.model);
folder.mkdirs();
try
{
FileUtils.write(file, output, StandardCharsets.UTF_8);
IModelLazyLoader previous = Blockbuster.proxy.pack.models.get(this.modelName);
/* Copy OBJ files */
if (previous != null)
{
previous.copyFiles(folder);
}
this.modelName = name;
Blockbuster.proxy.loadModels(false);
this.dirty(false);
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
/**
* Build the model from data model
*/
public void rebuildModel()
{
ModelPose oldPose = this.renderModel.pose;
this.renderModel.delete();
this.renderModel = this.buildModel();
this.modelRenderer.model = this.renderModel;
if (this.model != null)
{
this.renderModel.pose = oldPose;
this.modelRenderer.setPose(oldPose);
this.poseEditor.set(this.transform);
}
this.dirty();
}
/**
* Build the model from data model
*
* TODO: optimize by rebuilding only one limb
*/
public ModelCustom buildModel()
{
try
{
ModelExtrudedLayer.clearByModel(this.renderModel);
return this.modelEntry.loadClientModel(this.modelName, this.model);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Set a model from the repository
*/
public void setModel(String name)
{
ModelCustom model = ModelCustom.MODELS.get(name);
if (model != null)
{
this.setModel(name, model.model, Blockbuster.proxy.pack.models.get(name));
}
}
public void setModel(String name, Model model, IModelLazyLoader loader)
{
this.dirty(false);
this.modelName = name;
this.model = model.copy();
this.modelEntry = loader;
this.renderModel = this.buildModel();
this.modelRenderer.model = this.renderModel;
this.modelRenderer.texture = this.getFirstResourceLocation();
this.modelRenderer.limb = this.limb;
this.modelRenderer.setPose(this.pose);
this.limbs.fillData(model);
this.poses.fillData(model);
this.options.fillData(model);
this.setPose("standing", true);
this.setLimb(this.model.limbs.keySet().iterator().next());
}
/**
* Get the first available resource location for this model
*/
private ResourceLocation getFirstResourceLocation()
{
ResourceLocation rl = this.model.defaultTexture;
if (rl != null && rl.getResourcePath().isEmpty())
{
rl = null;
}
if (rl == null)
{
FolderEntry folder = ClientProxy.tree.getByPath(this.modelName + "/skins", null);
if (folder != null)
{
for (AbstractEntry file : folder.getEntries())
{
if (file instanceof mchorse.mclib.utils.files.entries.FileEntry)
{
rl = ((mchorse.mclib.utils.files.entries.FileEntry) file).resource;
}
}
}
}
return rl == null ? RLUtils.create("blockbuster", "textures/entity/actor.png") : rl;
}
@Override
public void draw(GuiContext context)
{
if (this.models.isVisible())
{
this.openModels.area.draw(0xaa000000);
}
else if (this.poses.isVisible())
{
this.openPoses.area.draw(0xaa000000);
}
else if (this.options.isVisible())
{
this.openOptions.area.draw(0xaa000000);
}
if (this.modelRenderer.swinging)
{
this.running.area.draw(0x66000000);
}
if (this.held)
{
this.items.area.draw(0x66000000);
}
if (this.modelRenderer.aabb)
{
this.hitbox.area.draw(0x66000000);
}
if (this.modelRenderer.looking)
{
this.looking.area.draw(0x66000000);
}
super.draw(context);
}
public static class GuiModelPoseTransformations extends GuiPoseTransformations
{
public GuiModelEditorPanel panel;
public GuiModelPoseTransformations(Minecraft mc, GuiModelEditorPanel panel)
{
super(mc);
this.panel = panel;
}
@Override
public void setT(double x, double y, double z)
{
super.setT(x, y, z);
this.panel.dirty();
}
@Override
public void setS(double x, double y, double z)
{
super.setS(x, y, z);
this.panel.dirty();
}
@Override
public void setR(double x, double y, double z)
{
super.setR(x, y, z);
this.panel.dirty();
}
}
} | 14,853 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelUtils.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/utils/ModelUtils.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils;
import java.io.StringWriter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.json.ModelAdapter;
import mchorse.blockbuster.api.json.ModelLimbAdapter;
import mchorse.blockbuster.api.json.ModelPoseAdapter;
/**
* Model utilities
*
* This code might be transferred to Metamorph, since this code is actually
* supposed to be in {@link Model} class.
*/
public class ModelUtils
{
/**
* Save model to JSON
*
* This method is responsible for making the JSON output pretty printed and
* 4 spaces indented (fuck 2 space indentation).
*/
public static String toJson(Model model)
{
GsonBuilder builder = new GsonBuilder().setPrettyPrinting();
builder.registerTypeAdapter(Model.class, new ModelAdapter());
builder.registerTypeAdapter(ModelLimb.class, new ModelLimbAdapter());
builder.registerTypeAdapter(ModelPose.class, new ModelPoseAdapter());
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
jsonWriter.setIndent(" ");
gson.toJson(model, Model.class, jsonWriter);
String output = writer.toString();
/* Prettify arrays */
output = output.replaceAll("\\n\\s+(?=-?\\d|\\])", " ");
return output;
}
} | 1,663 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiTwoElement.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/utils/GuiTwoElement.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.resizers.Flex;
import net.minecraft.client.Minecraft;
import java.util.function.Consumer;
public class GuiTwoElement extends GuiElement
{
public GuiTrackpadElement a;
public GuiTrackpadElement b;
public Double[] array;
public GuiTwoElement(Minecraft mc, Consumer<Double[]> callback)
{
super(mc);
this.array = new Double[] {0D, 0D};
this.a = new GuiTrackpadElement(mc, (value) ->
{
this.array[0] = value;
if (callback != null)
{
callback.accept(this.array);
}
});
this.b = new GuiTrackpadElement(mc, (value) ->
{
this.array[1] = value;
if (callback != null)
{
callback.accept(this.array);
}
});
this.flex().h(20).row(5);
this.add(this.a, this.b);
}
public void setLimit(int min, int max)
{
this.a.limit(min, max);
this.b.limit(min, max);
}
public void setLimit(int min, int max, boolean integer)
{
this.a.limit(min, max, integer);
this.b.limit(min, max, integer);
}
public void setValues(double a, double b)
{
this.a.setValue(a);
this.b.setValue(b);
this.array[0] = a;
this.array[1] = b;
}
} | 1,588 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiPoseTransformations.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/utils/GuiPoseTransformations.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.mclib.client.gui.framework.elements.input.GuiTransformations;
import net.minecraft.client.Minecraft;
public class GuiPoseTransformations extends GuiTransformations
{
public ModelTransform trans;
public ModelTransform oldTransform;
public GuiPoseTransformations(Minecraft mc)
{
super(mc);
}
public void set(ModelTransform trans)
{
this.set(trans, null);
}
public void set(ModelTransform trans, ModelTransform oldTransform)
{
this.trans = trans;
this.oldTransform = oldTransform;
if (trans != null)
{
this.fillT(trans.translate[0], trans.translate[1], trans.translate[2]);
this.fillS(trans.scale[0], trans.scale[1], trans.scale[2]);
this.fillR(trans.rotate[0], trans.rotate[1], trans.rotate[2]);
}
}
@Override
public void localTranslate(double x, double y, double z)
{
this.trans.addTranslation(x, y, z, GuiStaticTransformOrientation.getOrientation());
this.fillT(this.trans.translate[0], this.trans.translate[1], this.trans.translate[2]);
}
@Override
public void setT(double x, double y, double z)
{
this.trans.translate[0] = (float) x;
this.trans.translate[1] = (float) y;
this.trans.translate[2] = (float) z;
}
@Override
public void setS(double x, double y, double z)
{
this.trans.scale[0] = (float) x;
this.trans.scale[1] = (float) y;
this.trans.scale[2] = (float) z;
}
@Override
public void setR(double x, double y, double z)
{
this.trans.rotate[0] = (float) x;
this.trans.rotate[1] = (float) y;
this.trans.rotate[2] = (float) z;
}
@Override
protected void reset()
{
if (this.oldTransform == null)
{
super.reset();
}
else
{
this.fillSetT(this.oldTransform.translate[0], this.oldTransform.translate[1], this.oldTransform.translate[2]);
this.fillSetS(this.oldTransform.scale[0], this.oldTransform.scale[1], this.oldTransform.scale[2]);
this.fillSetR(this.oldTransform.rotate[0], this.oldTransform.rotate[1], this.oldTransform.rotate[2]);
}
}
} | 2,394 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiTextureCanvas.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/utils/GuiTextureCanvas.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs.GuiModelLimbs;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiCanvasEditor;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.Area;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
public class GuiTextureCanvas extends GuiCanvasEditor
{
public GuiTrackpadElement x;
public GuiTrackpadElement y;
public GuiIconElement close;
public GuiModelLimbs panel;
public GuiTextureCanvas(Minecraft mc, GuiModelLimbs panel)
{
super(mc);
this.panel = panel;
this.close = new GuiIconElement(mc, Icons.CLOSE, (b) -> this.toggleVisible());
this.close.flex().relative(this).x(1F, -25).y(5);
this.x = new GuiTrackpadElement(mc, (value) ->
{
this.panel.getPanel().limb.texture[0] = value.intValue();
this.panel.getPanel().rebuildModel();
});
this.x.limit(0, 8192, true);
this.y = new GuiTrackpadElement(mc, (value) ->
{
this.panel.getPanel().limb.texture[1] = value.intValue();
this.panel.getPanel().rebuildModel();
});
this.y.limit(0, 8192, true);
this.editor.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.texture")).background(), this.x, this.y);
this.add(this.editor, this.close);
this.markContainer();
}
@Override
protected boolean shouldDrawCanvas(GuiContext context)
{
return this.panel.getPanel().modelRenderer.texture != null;
}
@Override
protected void drawCanvasFrame(GuiContext guiContext)
{
ResourceLocation location = this.panel.getPanel().modelRenderer.texture;
Area area = this.calculate(-this.w / 2, -this.h / 2, this.w / 2, this.h / 2);
this.mc.renderEngine.bindTexture(location);
GuiDraw.drawBillboard(area.x, area.y, 0, 0, area.w, area.h, area.w, area.h);
ModelLimb limb = this.panel.getPanel().limb;
int lx = limb.texture[0];
int ly = limb.texture[1];
int lw = limb.size[0];
int lh = limb.size[1];
int ld = limb.size[2];
/* Top and bottom */
area = this.calculateRelative(lx + ld, ly, lx + ld + lw, ly + ld);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0x5500ff00);
area = this.calculateRelative(lx + ld + lw, ly, lx + ld + lw + lw, ly + ld);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0x5500ffff);
/* Front and back */
area = this.calculateRelative(lx + ld, ly + ld, lx + ld + lw, ly + ld + lh);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0x550000ff);
area = this.calculateRelative(lx + ld * 2 + lw, ly + ld, lx + ld * 2 + lw * 2, ly + ld + lh);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0x55ff00ff);
/* Left and right */
area = this.calculateRelative(lx, ly + ld, lx + ld, ly + ld + lh);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0x55ff0000);
area = this.calculateRelative(lx + ld + lw, ly + ld, lx + ld * 2 + lw, ly + ld + lh);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0x55ffff00);
/* Holes */
area = this.calculateRelative(lx, ly, lx + ld, ly + ld);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0xdd000000);
area = this.calculateRelative(lx + ld + lw * 2, ly, lx + ld * 2 + lw * 2, ly + ld);
Gui.drawRect(area.x, area.y, area.ex(), area.ey(), 0xdd000000);
/* Outline */
area = this.calculateRelative(lx, ly, lx + ld * 2 + lw * 2, ly + ld + lh);
GuiDraw.drawOutline(area.x, area.y, area.ex(), area.ey(), 0xffff0000);
}
} | 4,313 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBBModelRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/utils/GuiBBModelRenderer.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils;
import java.util.List;
import java.util.Map;
import mchorse.mclib.client.gui.framework.elements.input.GuiTransformations;
import mchorse.mclib.utils.MatrixUtils;
import mchorse.mclib.utils.RenderingUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.formats.obj.ShapeKey;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs.GuiAnchorModal;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import mchorse.blockbuster.client.render.RenderCustomModel;
import mchorse.blockbuster.client.render.layer.LayerHeldItem;
import mchorse.mclib.client.Draw;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.utils.DummyEntity;
import mchorse.mclib.utils.Interpolations;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3d;
/**
* Model renderer which renders Blockbuster models
*/
public class GuiBBModelRenderer extends GuiModelRenderer
{
public boolean swinging;
private float swing;
private float swingAmount;
private int swipe;
public boolean items;
public boolean aabb;
public boolean origin;
public boolean looking = true;
public Map<String, ResourceLocation> materials;
public ResourceLocation texture;
public ModelCustom model;
public ModelLimb limb;
public GuiAnchorModal anchorPreview;
private ModelPose pose;
private List<ShapeKey> shapes;
public static void renderItems(EntityLivingBase entity, ModelCustom model)
{
ItemStack main = entity.getHeldItemMainhand();
ItemStack offhand = entity.getHeldItemOffhand();
if (!offhand.isEmpty() || !main.isEmpty())
{
GlStateManager.pushMatrix();
LayerHeldItem.renderHeldItem(entity, offhand, model, ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND, EnumHandSide.LEFT);
LayerHeldItem.renderHeldItem(entity, main, model, ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND, EnumHandSide.RIGHT);
GlStateManager.popMatrix();
}
}
public GuiBBModelRenderer(Minecraft mc)
{
super(mc);
}
public void swipe()
{
this.swipe = 6;
}
public void toggleItems()
{
this.items = !this.items;
((DummyEntity) this.entity).toggleItems(this.items);
}
/**
* Update logic
*/
@Override
protected void update()
{
super.update();
if (this.swipe > -1)
{
this.swipe--;
}
if (this.swinging)
{
this.swing += 0.75F;
this.swingAmount = 1.0F;
}
else
{
this.swing = 0.0F;
this.swingAmount = 0.0F;
}
}
@Override
public boolean mouseClicked(GuiContext context)
{
boolean result = super.mouseClicked(context);
if (this.dragging && GuiScreen.isCtrlKeyDown())
{
this.tryPicking = true;
this.dragging = false;
}
return result;
}
@Override
public void mouseReleased(GuiContext context)
{
super.mouseReleased(context);
this.tryPicking = false;
}
protected float getScale()
{
return 1;
}
@Override
protected void drawUserModel(GuiContext context)
{
if (this.model == null)
{
return;
}
float partial = context.partialTicks;
float headYaw = this.yaw - (this.customEntity ? this.entityYawBody : 0);
float headPitch = -this.pitch;
final float factor = 1 / 16F;
float limbSwing = this.swinging ? this.swing + partial : 0;
if (!this.looking)
{
headYaw = this.customEntity ? this.entityYawHead - this.entityYawBody : 0;
headPitch = this.customEntity ? this.entityPitch : 0;
}
this.updateModel(limbSwing, headYaw, headPitch, factor, partial);
float scale = this.getScale();
GlStateManager.pushMatrix();
GlStateManager.scale(model.model.scale[0], model.model.scale[1], model.model.scale[2]);
GlStateManager.scale(-1.0F * scale, -1.0F * scale, 1.0F * scale);
GlStateManager.translate(0.0F, -1.501F, 0.0F);
GlStateManager.rotate(180 + (this.customEntity ? this.entityYawBody : 0), 0, 1, 0);
if (this.texture != null)
{
RenderCustomModel.bindLastTexture(this.texture);
}
this.tryPicking(context);
this.renderModel(this.entity, headYaw, headPitch, this.customEntity ? this.entityTicksExisted : this.timer, context.mouseX, context.mouseY, partial, factor);
if (this.items)
{
renderItems(this.entity, this.model);
}
/* Render highlighting things on top */
this.updateModel(limbSwing, headYaw, headPitch, factor, partial);
GlStateManager.pushMatrix();
GlStateManager.disableTexture2D();
GlStateManager.disableDepth();
GlStateManager.disableLighting();
if (this.limb != null)
{
ModelCustomRenderer targetLimb = this.model.get(this.limb.name);
if (targetLimb != null)
{
if (model.limbs.length > 1)
{
if (targetLimb.getClass() != ModelCustomRenderer.class)
{
this.renderObjHighlight(targetLimb);
}
else
{
targetLimb.postRender(1F / 16F);
this.renderLimbHighlight(this.limb);
}
}
else
{
if (this.origin)
{
targetLimb.postRender(1F / 16F);
this.drawAxis(targetLimb, 0.25F);
}
}
this.renderAnchorPreview(targetLimb);
}
}
GlStateManager.enableLighting();
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
GlStateManager.popMatrix();
GlStateManager.popMatrix();
if (this.aabb)
{
this.renderAABB();
}
}
protected void drawAxis(ModelCustomRenderer target, float length)
{
GlStateManager.pushMatrix();
if (GuiTransformations.GuiStaticTransformOrientation.getOrientation() == GuiTransformations.TransformOrientation.GLOBAL)
{
RenderingUtils.glRevertRotationScale(new Vector3d(target.rotateAngleX, target.rotateAngleY, target.rotateAngleZ),
new Vector3d(target.scaleX, target.scaleY, target.scaleZ),
MatrixUtils.RotationOrder.XYZ);
}
Draw.axis(length);
GlStateManager.popMatrix();
}
protected void updateModel(float limbSwing, float headYaw, float headPitch, float factor, float partial)
{
this.model.materials = this.materials;
this.model.shapes = this.shapes;
this.model.pose = this.pose;
this.model.swingProgress = this.swipe == -1 ? 0 : MathHelper.clamp(1.0F - (this.swipe - 1.0F * partial) / 6.0F, 0.0F, 1.0F);
this.model.setLivingAnimations(this.entity, headYaw, headPitch, partial);
this.model.setRotationAngles(limbSwing, this.swingAmount, this.customEntity ? this.entityTicksExisted : this.timer, headYaw, headPitch, factor, this.entity);
}
protected void renderModel(EntityLivingBase dummy, float headYaw, float headPitch, int timer, int yaw, int pitch, float partial, float factor)
{
this.model.render(dummy, headYaw, headPitch, timer, yaw, pitch, factor);
}
@Override
protected void drawForStencil(GuiContext context)
{
if (this.model != null)
{
this.model.renderForStencil(this.entity, this.swing + context.partialTicks, this.swingAmount, this.customEntity ? this.entityTicksExisted : this.timer, this.yaw, this.pitch, 1 / 16F);
}
}
@Override
protected String getStencilValue(int value)
{
return this.model.limbs[value - 1].limb.name;
}
/**
* Render limb highlight and the anchor and origin point of the limb
*/
protected void renderLimbHighlight(ModelLimb limb)
{
float f = 1F / 16F;
float w = limb.size[0] * f;
float h = limb.size[1] * f;
float d = limb.size[2] * f;
float o = limb.sizeOffset * f;
float minX = 0;
float minY = 0;
float minZ = 0;
float maxX = w;
float maxY = h;
float maxZ = d;
float alpha = 0.2F;
minX -= w * limb.anchor[0] + 0.1F * f;
maxX -= w * limb.anchor[0] - 0.1F * f;
minY -= h * limb.anchor[1] + 0.1F * f;
maxY -= h * limb.anchor[1] - 0.1F * f;
minZ -= d * limb.anchor[2] + 0.1F * f;
maxZ -= d * limb.anchor[2] - 0.1F * f;
minX *= -1;
maxX *= -1;
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
Draw.cube(minX + o, minY - o, minZ -o, maxX - o, maxY + o, maxZ + o, 0F, 0.5F, 1F, alpha);
GlStateManager.disableAlpha();
GlStateManager.disableBlend();
if (this.origin)
{
this.drawAxis(this.model.get(limb.name), 0.25F);
}
}
protected void renderObjHighlight(ModelCustomRenderer renderer)
{
float f = 1F / 16F;
GlStateManager.pushMatrix();
GL11.glClearStencil(0);
GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT);
GL11.glEnable(GL11.GL_STENCIL_TEST);
GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_REPLACE, GL11.GL_REPLACE);
GL11.glColorMask(false, false, false, false);
if (renderer.parent != null)
{
renderer.parent.postRender(f);
}
List<ModelRenderer> children = renderer.childModels;
renderer.childModels = null;
renderer.setupStencilRendering(1);
renderer.render(f);
renderer.childModels = children;
GL11.glStencilMask(0);
GL11.glStencilFunc(GL11.GL_EQUAL, 1, -1);
GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP);
GL11.glColorMask(true, true, true, true);
GL11.glLoadIdentity();
GlStateManager.matrixMode(GL11.GL_PROJECTION);
GlStateManager.pushMatrix();
GL11.glLoadIdentity();
GlStateManager.enableBlend();
GlStateManager.color(0F, 0.5F, 1F, 0.2F);
GL11.glBegin(GL11.GL_TRIANGLE_STRIP);
GL11.glVertex3f(-1.0F, -1.0F, 0.0F);
GL11.glVertex3f(1.0F, -1.0F, 0.0F);
GL11.glVertex3f(-1.0F, 1.0F, 0.0F);
GL11.glVertex3f(1.0F, 1.0F, 0.0F);
GL11.glEnd();
GL11.glFlush();
GlStateManager.color(1F, 1F, 1F, 1F);
GlStateManager.disableBlend();
GL11.glStencilMask(-1);
GL11.glStencilFunc(GL11.GL_NEVER, 0, 0);
GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP);
GL11.glDisable(GL11.GL_STENCIL_TEST);
GlStateManager.popMatrix();
GlStateManager.matrixMode(GL11.GL_MODELVIEW);
GlStateManager.popMatrix();
renderer.postRender(f);
if (this.origin)
{
this.drawAxis(renderer, 0.25F);
}
}
/**
* Render model's hitbox
*/
protected void renderAABB()
{
ModelPose current = this.pose;
float minX = -current.size[0] / 2.0F;
float maxX = current.size[0] / 2.0F;
float minY = 0.0F;
float maxY = current.size[1];
float minZ = -current.size[0] / 2.0F;
float maxZ = current.size[0] / 2.0F;
GlStateManager.depthMask(false);
GlStateManager.disableTexture2D();
GlStateManager.disableLighting();
GlStateManager.disableCull();
GlStateManager.disableBlend();
/* This is necessary to hid / lines which are used to reduce
* amount of drawing operations */
GlStateManager.enableAlpha();
RenderGlobal.drawBoundingBox(minX, minY, minZ, maxX, maxY, maxZ, 1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.enableCull();
GlStateManager.disableBlend();
GlStateManager.depthMask(true);
}
protected void renderAnchorPreview(ModelCustomRenderer renderer)
{
if (this.anchorPreview != null && renderer.min != null && renderer.max != null)
{
float ax = (float) this.anchorPreview.vector.a.value;
float ay = (float) this.anchorPreview.vector.b.value;
float az = (float) this.anchorPreview.vector.c.value;
float dx = renderer.max.x - renderer.min.x;
float dy = renderer.max.y - renderer.min.y;
float dz = renderer.max.z - renderer.min.z;
float x = renderer.min.x + Interpolations.lerp(0, dx, ax) - this.limb.origin[0];
float y = renderer.min.y + Interpolations.lerp(0, dy, ay) - this.limb.origin[1];
float z = renderer.min.z + Interpolations.lerp(0, dz, az) - this.limb.origin[2];
GlStateManager.disableLighting();
GlStateManager.disableTexture2D();
GlStateManager.disableDepth();
GlStateManager.pushMatrix();
GlStateManager.translate(-x, -y, z);
Draw.point(0, 0, 0);
GlStateManager.popMatrix();
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
}
}
public void setPose(ModelPose pose)
{
this.setPose(pose, pose == null ? null : pose.shapes);
}
public void setPose(ModelPose pose, List<ShapeKey> shapes)
{
this.pose = pose;
this.shapes = shapes;
}
} | 14,847 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiThreeElement.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/utils/GuiThreeElement.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.resizers.Flex;
import net.minecraft.client.Minecraft;
import java.util.function.Consumer;
public class GuiThreeElement extends GuiTwoElement
{
public GuiTrackpadElement c;
public GuiThreeElement(Minecraft mc, Consumer<Double[]> callback)
{
super(mc, callback);
this.array = new Double[] {0D, 0D, 0D};
this.c = new GuiTrackpadElement(mc, (value) ->
{
this.array[2] = value;
if (callback != null)
{
callback.accept(this.array);
}
});
this.add(this.c);
}
@Override
public void setLimit(int min, int max)
{
super.setLimit(min, max);
this.c.min = min;
this.c.max = max;
}
@Override
public void setLimit(int min, int max, boolean integer)
{
super.setLimit(min, max, integer);
this.c.limit(min, max, integer);
}
public void setValues(double a, double b, double c)
{
this.setValues(a, b);
this.c.setValue(c);
this.array[2] = c;
}
} | 1,260 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelLimbs.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/tabs/GuiModelLimbs.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs;
import javax.vecmath.Matrix4f;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelLimb.ArmorSlot;
import mchorse.blockbuster.api.ModelLimb.Holding;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.GuiModelEditorPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiTextureCanvas;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiThreeElement;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import mchorse.blockbuster.client.model.ModelOBJRenderer;
import mchorse.blockbuster.client.model.ModelVoxRenderer;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.GuiScrollElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.context.GuiSimpleContextMenu;
import mchorse.mclib.client.gui.framework.elements.input.GuiColorElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiListModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiMessageModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.Interpolations;
import net.minecraft.client.Minecraft;
import javax.vecmath.Vector3f;
public class GuiModelLimbs extends GuiModelEditorTab
{
private GuiIconElement addLimb;
private GuiIconElement dupeLimb;
private GuiIconElement removeLimb;
private GuiIconElement renameLimb;
private GuiIconElement parentLimb;
private GuiStringListElement limbs;
private GuiScrollElement scroll;
/* First category */
private GuiThreeElement size;
private GuiTrackpadElement sizeOffset;
private GuiTrackpadElement itemScale;
private GuiButtonElement texture;
private GuiThreeElement anchor;
private GuiThreeElement origin;
private GuiTextureCanvas textureEditor;
/* Second category */
private GuiToggleElement mirror;
private GuiToggleElement lighting;
private GuiToggleElement shading;
private GuiToggleElement smooth;
private GuiToggleElement is3D;
private GuiElement colors;
private GuiColorElement color;
private GuiColorElement specular;
private GuiCirculateElement holding;
private GuiCirculateElement slot;
private GuiToggleElement hold;
private GuiToggleElement swiping;
private GuiToggleElement lookX;
private GuiToggleElement lookY;
private GuiToggleElement swinging;
private GuiToggleElement idle;
private GuiToggleElement invert;
private GuiToggleElement wheel;
private GuiToggleElement wing;
private GuiToggleElement roll;
private GuiToggleElement cape;
private GuiElement vanillaPanel;
private GuiElement objPanel;
private float lastAnchorX;
private float lastAnchorY;
private float lastAnchorZ;
public GuiModelLimbs(Minecraft mc, GuiModelEditorPanel panel)
{
super(mc, panel);
this.title = IKey.lang("blockbuster.gui.me.limbs.title");
this.limbs = new GuiStringListElement(mc, (str) -> this.setLimb(str.get(0)));
this.limbs.background().flex().relative(this).y(20).w(1F).h(100);
this.scroll = new GuiScrollElement(mc);
this.scroll.scroll.scrollSpeed = 15;
this.scroll.flex().relative(this.limbs).y(1F).w(1F).hTo(this.area, 1F).column(5).vertical().stretch().scroll().height(20).padding(10);
this.textureEditor = new GuiTextureCanvas(mc, this);
this.textureEditor.flex().relative(this.limbs).y(1F).w(1F).hTo(this.area, 1F);
/* First category */
this.size = new GuiThreeElement(mc, (values) ->
{
this.panel.limb.size[0] = values[0].intValue();
this.panel.limb.size[1] = values[1].intValue();
this.panel.limb.size[2] = values[2].intValue();
this.panel.rebuildModel();
});
this.size.setLimit(0, 8192, true);
this.sizeOffset = new GuiTrackpadElement(mc, (value) ->
{
this.panel.limb.sizeOffset = value.floatValue();
this.panel.rebuildModel();
});
this.itemScale = new GuiTrackpadElement(mc, (value) ->
{
this.panel.limb.itemScale = value.floatValue();
this.panel.dirty();
});
this.texture = new GuiButtonElement(mc, IKey.comp(IKey.lang("blockbuster.gui.edit"), IKey.str("...")), (b) ->
{
this.textureEditor.toggleVisible();
this.textureEditor.setSize(this.panel.model.texture[0], this.panel.model.texture[1]);
});
this.anchor = new GuiThreeElement(mc, (values) ->
{
if (this.is3D.isVisible())
{
this.fixLimbPosition(values[0].floatValue(), values[1].floatValue(), values[2].floatValue());
this.lastAnchorX = this.panel.limb.anchor[0] = values[0].floatValue();
this.lastAnchorY = this.panel.limb.anchor[1] = values[1].floatValue();
this.lastAnchorZ = this.panel.limb.anchor[2] = values[2].floatValue();
}
else
{
this.panel.limb.anchor[0] = values[0].floatValue();
this.panel.limb.anchor[1] = values[1].floatValue();
this.panel.limb.anchor[2] = values[2].floatValue();
}
this.panel.rebuildModel();
});
this.origin = new GuiThreeElement(mc, (values) ->
{
this.fixLimbPosition(values[0].floatValue(), values[1].floatValue(), values[2].floatValue());
this.lastAnchorX = this.panel.limb.origin[0] = values[0].floatValue();
this.lastAnchorY = this.panel.limb.origin[1] = values[1].floatValue();
this.lastAnchorZ = this.panel.limb.origin[2] = values[2].floatValue();
this.panel.rebuildModel();
});
this.origin.context(() ->
{
ModelCustomRenderer renderer = this.panel.renderModel.get(this.panel.limb.name);
if (renderer != null && renderer.min != null && renderer.max != null)
{
return new GuiSimpleContextMenu(this.mc)
.action(Icons.FULLSCREEN, IKey.lang("blockbuster.gui.me.limbs.context.anchor_setup"), () -> this.setupAnchorPoint(renderer, false))
.action(Icons.DOWNLOAD, IKey.lang("blockbuster.gui.me.limbs.context.anchor_move"), () -> this.setupAnchorPoint(renderer, true));
}
return null;
});
this.slot = new GuiCirculateElement(mc, (b) ->
{
this.panel.limb.slot = ArmorSlot.values()[this.slot.getValue()];
this.panel.dirty();
});
this.slot.tooltip(IKey.lang("blockbuster.gui.me.limbs.slot"));
this.hold = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.holding"), false, (b) ->
{
this.panel.limb.hold = b.isToggled();
this.panel.dirty();
});
for (ArmorSlot slot : ArmorSlot.values())
{
this.slot.addLabel(IKey.lang("blockbuster.gui.me.limbs.slots." + slot.name));
}
/* Second category */
this.color = new GuiColorElement(mc, (eh) ->
{
Color color = this.color.picker.color;
this.panel.limb.color[0] = color.r;
this.panel.limb.color[1] = color.g;
this.panel.limb.color[2] = color.b;
this.panel.limb.opacity = color.a;
this.panel.dirty();
});
this.color.picker.editAlpha();
this.color.tooltip(IKey.lang("blockbuster.gui.me.limbs.color"));
this.specular = new GuiColorElement(mc, (eh) ->
{
Color color = this.specular.picker.color;
this.panel.limb.specular = color.getRGBAColor();
this.panel.dirty();
});
this.specular.picker.editAlpha();
this.specular.tooltip(IKey.lang("blockbuster.gui.me.limbs.specular"));
this.mirror = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.mirror"), false, (b) ->
{
this.panel.limb.mirror = b.isToggled();
this.panel.rebuildModel();
});
this.mirror.flex().h(20);
this.lighting = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.lighting"), false, (b) ->
{
this.panel.limb.lighting = b.isToggled();
this.panel.dirty();
});
this.shading = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.shading"), false, (b) ->
{
this.panel.limb.shading = b.isToggled();
this.panel.dirty();
});
this.smooth = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.smooth"), false, (b) ->
{
this.panel.limb.smooth = b.isToggled();
this.panel.dirty();
});
this.is3D = new GuiToggleElement(mc, IKey.str("3D"), false, (b) ->
{
this.panel.limb.is3D = b.isToggled();
this.panel.dirty();
});
this.holding = new GuiCirculateElement(mc, (b) ->
{
this.panel.limb.holding = Holding.values()[this.holding.getValue()];
this.panel.rebuildModel();
});
this.holding.tooltip(IKey.lang("blockbuster.gui.me.limbs.hold"));
this.holding.addLabel(IKey.lang("blockbuster.gui.me.limbs.none"));
this.holding.addLabel(IKey.lang("blockbuster.gui.me.limbs.right"));
this.holding.addLabel(IKey.lang("blockbuster.gui.me.limbs.left"));
this.swiping = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.swiping"), false, (b) ->
{
this.panel.limb.swiping = b.isToggled();
this.panel.dirty();
});
this.lookX = new GuiToggleElement(mc, IKey.comp(IKey.lang("blockbuster.gui.me.limbs.looking"), IKey.str(" X")), false, (b) ->
{
this.panel.limb.lookX = b.isToggled();
this.panel.dirty();
});
this.lookY = new GuiToggleElement(mc, IKey.comp(IKey.lang("blockbuster.gui.me.limbs.looking"), IKey.str(" Y")), false, (b) ->
{
this.panel.limb.lookY = b.isToggled();
this.panel.dirty();
});
this.swinging = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.swinging"), false, (b) ->
{
this.panel.limb.swinging = b.isToggled();
this.panel.dirty();
});
this.idle = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.idle"), false, (b) ->
{
this.panel.limb.idle = b.isToggled();
this.panel.dirty();
});
this.invert = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.invert"), false, (b) ->
{
this.panel.limb.invert = b.isToggled();
this.panel.dirty();
});
this.wheel = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.wheel"), false, (b) ->
{
this.panel.limb.wheel = b.isToggled();
this.panel.dirty();
});
this.wing = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.wing"), false, (b) ->
{
this.panel.limb.wing = b.isToggled();
this.panel.dirty();
});
this.roll = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.roll"), false, (b) ->
{
this.panel.limb.roll = b.isToggled();
this.panel.dirty();
});
this.cape = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.limbs.cape"), false, (b) ->
{
this.panel.limb.cape = b.isToggled();
this.panel.dirty();
});
this.vanillaPanel = Elements.column(mc, 5);
this.vanillaPanel.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.size")).background(), this.size);
this.vanillaPanel.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.size_offset")).background(), this.sizeOffset);
this.vanillaPanel.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.texture")).background().marginTop(12), Elements.row(mc, 5, 0, 20, this.texture, this.mirror));
this.objPanel = Elements.column(mc, 5);
this.objPanel.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.origin")).background(), this.origin);
GuiElement appearance = new GuiElement(mc);
appearance.flex().grid(5).items(2).resizes(true);
appearance.add(this.lighting, this.shading);
appearance.add(this.smooth, this.is3D);
this.colors = new GuiElement(mc);
this.colors.flex().grid(5).items(1).resizes(true);
this.colors.add(this.color);
GuiElement animation = new GuiElement(mc);
animation.flex().grid(5).items(2).resizes(true);
animation.add(this.lookX, this.lookY);
animation.add(this.idle, this.swinging);
animation.add(this.invert, this.swiping);
animation.add(this.hold, this.wheel);
animation.add(this.wing, this.roll);
animation.add(this.cape);
this.scroll.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.anchor")).background().marginTop(12), this.anchor);
this.scroll.add(Elements.row(mc, 5, this.slot, this.holding));
this.scroll.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.item_scale")).background(), this.itemScale);
this.scroll.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.appearance")).background().marginTop(12), appearance, this.colors);
this.scroll.add(Elements.label(IKey.lang("blockbuster.gui.me.limbs.animation")).background().marginTop(12), animation);
/* Buttons */
this.addLimb = new GuiIconElement(mc, Icons.ADD, (b) -> this.addLimb());
this.dupeLimb = new GuiIconElement(mc, Icons.DUPE, (b) -> this.dupeLimb());
this.removeLimb = new GuiIconElement(mc, Icons.REMOVE, (b) -> this.removeLimb());
this.renameLimb = new GuiIconElement(mc, Icons.EDIT, (b) -> this.renameLimb());
this.parentLimb = new GuiIconElement(mc, Icons.LIMB, (b) -> this.parentLimb());
GuiElement sidebar = Elements.row(mc, 0, 0, 20, this.addLimb, this.dupeLimb, this.parentLimb, this.renameLimb, this.removeLimb);
sidebar.flex().relative(this).x(1F).h(20).anchorX(1F).row(0).resize();
this.add(sidebar, this.limbs, this.scroll, this.textureEditor);
}
private void setupAnchorPoint(ModelCustomRenderer renderer, boolean move)
{
GuiAnchorModal modal = new GuiAnchorModal(this.mc, IKey.lang("blockbuster.gui.me.limbs.anchor_modal"), (anchor) -> this.doSetupAnchorPoint(renderer, anchor, move));
this.panel.modelRenderer.anchorPreview = modal;
GuiModal.addFullModal(this, () -> modal);
}
private void doSetupAnchorPoint(ModelCustomRenderer renderer, Vector3f anchor, boolean move)
{
renderer.limb.origin[0] = Interpolations.lerp(renderer.min.x, renderer.max.x, anchor.x);
renderer.limb.origin[1] = Interpolations.lerp(renderer.min.y, renderer.max.y, anchor.y);
renderer.limb.origin[2] = Interpolations.lerp(renderer.min.z, renderer.max.z, anchor.z);
if (move)
{
float[] translate = this.panel.pose.limbs.get(renderer.limb.name).translate;
translate[0] = -renderer.limb.origin[0] * 16;
translate[1] = renderer.limb.origin[1] * 16;
translate[2] = -renderer.limb.origin[2] * 16;
}
this.panel.modelRenderer.anchorPreview = null;
this.panel.setLimb(renderer.limb.name);
this.panel.rebuildModel();
}
private void addLimb()
{
GuiModal.addFullModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.me.limbs.new_limb"), this::addLimb);
return modal.setValue(this.panel.limb.name);
});
}
private void addLimb(String text)
{
if (!this.panel.model.limbs.containsKey(text))
{
this.panel.model.addLimb(text);
this.limbs.add(text);
this.limbs.setCurrent(text);
this.panel.rebuildModel();
this.panel.setLimb(text);
}
}
private void dupeLimb()
{
if (this.getLimbClass(this.panel.limb) != ModelCustomRenderer.class)
{
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.lang("blockbuster.gui.me.limbs.obj_limb")));
return;
}
ModelLimb limb = this.panel.limb.clone();
/* It must be unique name */
while (this.panel.model.limbs.containsKey(limb.name))
{
limb.name += "_copy";
}
this.panel.model.addLimb(limb);
this.limbs.add(limb.name);
this.limbs.setCurrent(limb.name);
this.panel.rebuildModel();
this.panel.setLimb(limb.name);
}
private void removeLimb()
{
int size = this.panel.model.limbs.size();
if (this.getLimbClass(this.panel.limb) != ModelCustomRenderer.class)
{
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.lang("blockbuster.gui.me.limbs.obj_limb")));
}
else if (size == this.panel.model.getLimbCount(this.panel.limb))
{
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.lang("blockbuster.gui.me.limbs.last_limb")));
}
else
{
this.panel.model.removeLimb(this.panel.limb);
String newLimb = this.panel.model.limbs.keySet().iterator().next();
this.fillData(this.panel.model);
this.panel.rebuildModel();
this.panel.setLimb(newLimb);
}
}
private void renameLimb()
{
if (this.getLimbClass(this.panel.limb) != ModelCustomRenderer.class)
{
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.lang("blockbuster.gui.me.limbs.obj_limb")));
}
else
{
GuiModal.addFullModal(this, () -> new GuiPromptModal(mc, IKey.lang("blockbuster.gui.me.limbs.rename_limb"), this::renameLimb).setValue(this.panel.limb.name));
}
}
private void renameLimb(String text)
{
if (this.panel.model.renameLimb(this.panel.limb, text))
{
this.limbs.replace(text);
this.panel.rebuildModel();
}
}
private void parentLimb()
{
GuiModal.addFullModal(this, () ->
{
GuiListModal modal = new GuiListModal(mc, IKey.lang("blockbuster.gui.me.limbs.parent_limb"), this::parentLimb);
return modal.addValues(this.panel.model.limbs.keySet()).setValue(this.panel.limb.parent);
});
}
private void parentLimb(String text)
{
if (!this.panel.limb.name.equals(text))
{
this.panel.limb.parent = text;
this.panel.rebuildModel();
}
}
private void setLimb(String str)
{
this.panel.setLimb(str);
this.fillLimbData(this.panel.limb);
}
public void setCurrent(String str)
{
this.limbs.setCurrent(str);
this.fillLimbData(this.panel.limb);
}
public void fillData(Model model)
{
this.limbs.clear();
this.limbs.add(model.limbs.keySet());
this.limbs.sort();
this.textureEditor.setVisible(false);
}
public void fillLimbData(ModelLimb limb)
{
this.textureEditor.x.setValue(this.panel.limb.texture[0]);
this.textureEditor.y.setValue(this.panel.limb.texture[1]);
this.size.setValues(limb.size[0], limb.size[1], limb.size[2]);
this.sizeOffset.setValue(limb.sizeOffset);
this.itemScale.setValue(limb.itemScale);
this.anchor.setValues(limb.anchor[0], limb.anchor[1], limb.anchor[2]);
this.origin.setValues(limb.origin[0], limb.origin[1], limb.origin[2]);
this.color.picker.setColor(limb.color[0], limb.color[1], limb.color[2], limb.opacity);
this.mirror.toggled(limb.mirror);
this.lighting.toggled(limb.lighting);
this.shading.toggled(limb.shading);
this.smooth.toggled(limb.smooth);
this.is3D.toggled(limb.is3D);
this.holding.setValue(limb.holding.ordinal());
this.slot.setValue(limb.slot.ordinal());
this.hold.toggled(limb.hold);
this.swiping.toggled(limb.swiping);
this.lookX.toggled(limb.lookX);
this.lookY.toggled(limb.lookY);
this.swinging.toggled(limb.swinging);
this.idle.toggled(limb.idle);
this.invert.toggled(limb.invert);
this.wheel.toggled(limb.wheel);
this.wing.toggled(limb.wing);
this.roll.toggled(limb.roll);
this.cape.toggled(limb.cape);
boolean isObj = this.getLimbClass(limb) != ModelCustomRenderer.class;
boolean isVOX = this.getLimbClass(limb) == ModelVoxRenderer.class;
this.vanillaPanel.removeFromParent();
this.objPanel.removeFromParent();
this.is3D.setVisible(!isObj);
if (isObj)
{
this.lastAnchorX = limb.origin[0];
this.lastAnchorY = limb.origin[1];
this.lastAnchorZ = limb.origin[2];
this.scroll.prepend(this.objPanel);
}
else
{
this.lastAnchorX = limb.anchor[0];
this.lastAnchorY = limb.anchor[1];
this.lastAnchorZ = limb.anchor[2];
this.scroll.prepend(this.vanillaPanel);
}
if (isVOX)
{
if (!this.specular.hasParent())
{
this.colors.flex().grid(5).items(2).resizes(true);
this.colors.add(this.specular);
}
this.specular.picker.setColor(limb.specular);
}
else
{
this.specular.removeFromParent();
this.colors.flex().grid(5).items(1).resizes(true);
}
this.scroll.resize();
}
private void fixLimbPosition(float x, float y, float z)
{
Model model = this.panel.model;
ModelLimb limb = this.panel.limb;
ModelTransform transform = this.panel.transform;
Class<? extends ModelCustomRenderer> clazz = this.getLimbClass(limb);
Matrix4f mat = new Matrix4f();
mat.setIdentity();
mat.m03 = transform.translate[0];
mat.m13 = transform.translate[1];
mat.m23 = transform.translate[2];
Matrix4f mat2 = new Matrix4f();
mat2.rotZ((float) Math.toRadians(transform.rotate[2]));
mat.mul(mat2);
mat2.rotY((float) Math.toRadians(transform.rotate[1]));
mat.mul(mat2);
mat2.rotX((float) Math.toRadians(transform.rotate[0]));
mat.mul(mat2);
mat2.setIdentity();
mat2.m00 = transform.scale[0];
mat2.m11 = transform.scale[1];
mat2.m22 = transform.scale[2];
mat.mul(mat2);
if (clazz != ModelCustomRenderer.class)
{
if (clazz == ModelOBJRenderer.class)
{
mat2.setIdentity();
mat2.m00 = model.legacyObj || this.getLimbClass(this.panel.limb) == ModelVoxRenderer.class ? 16 : -16;
mat2.m11 = 16;
mat2.m22 = 16;
mat.mul(mat2);
}
mat2.setIdentity();
mat2.m03 = x - this.lastAnchorX;
mat2.m13 = y - this.lastAnchorY;
mat2.m23 = this.lastAnchorZ - z;
mat.mul(mat2);
}
else
{
mat2.setIdentity();
mat2.m00 = limb.size[0];
mat2.m11 = limb.size[1];
mat2.m22 = limb.size[2];
mat.mul(mat2);
mat2.setIdentity();
mat2.m03 = this.lastAnchorX - x;
mat2.m13 = this.lastAnchorY - y;
mat2.m23 = this.lastAnchorZ - z;
mat.mul(mat2);
}
transform.translate[0] = mat.m03;
transform.translate[1] = mat.m13;
transform.translate[2] = mat.m23;
}
private Class<? extends ModelCustomRenderer> getLimbClass(ModelLimb limb)
{
for (ModelCustomRenderer limbRenderer : this.panel.renderModel.limbs)
{
if (limbRenderer.limb.name.equals(limb.name))
{
return limbRenderer.getClass();
}
}
return null;
}
} | 25,359 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelList.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/tabs/GuiModelList.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderJSON;
import mchorse.blockbuster.api.resource.StreamEntry;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.GuiModelEditorPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiThreeElement;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiTwoElement;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.parsing.ModelExporter;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.GuiScrollElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringSearchListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiListModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiMessageModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.GuiUtils;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.ScrollArea;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Patterns;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.EntityEntry;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Pattern;
public class GuiModelList extends GuiModelEditorTab
{
public static final Pattern FILENAME_SLASHES = Pattern.compile(Patterns.FILENAME.pattern().replace("]*$","/]*$"));
public GuiStringSearchListElement models;
private GuiIconElement dupe;
private GuiIconElement export;
private GuiIconElement folder;
public GuiModelList(Minecraft mc, GuiModelEditorPanel panel)
{
super(mc, panel);
this.title = IKey.lang("blockbuster.gui.me.models.title");
this.models = new GuiStringSearchListElement(mc, (str) -> this.panel.setModel(str.get(0)));
this.models.flex().relative(this.area).y(20).w(140).h(1, -20);
this.models.list.scroll.scrollSpeed = 16;
this.dupe = new GuiIconElement(mc, Icons.DUPE, (b) -> this.saveModel());
this.export = new GuiIconElement(mc, Icons.UPLOAD, (b) -> this.exportModel());
this.folder = new GuiIconElement(mc, Icons.FOLDER, (b) -> this.openFolder());
GuiElement sidebar = Elements.row(mc, 0, 0, 20, this.dupe, this.export, this.folder);
sidebar.flex().relative(this.models).x(1F).y(-20).h(20).anchorX(1F).row(0).resize();
this.add(this.models, sidebar);
}
public void updateModelList()
{
String current = this.models.list.getCurrentFirst();
this.models.list.clear();
this.models.list.add(ModelCustom.MODELS.keySet());
this.models.list.sort();
if (current == null)
{
current = "steve";
}
this.models.list.setCurrentScroll(current);
}
private void saveModel()
{
GuiModal.addFullModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(mc, IKey.lang("blockbuster.gui.me.models.name"), this::saveModel).setValue(this.panel.modelName);
modal.text.validator((string) -> FILENAME_SLASHES.matcher(string).find());
return modal;
});
}
private void saveModel(String name)
{
boolean exists = ModelCustom.MODELS.containsKey(name);
if (!exists)
{
if (!this.panel.saveModel(name))
{
return;
}
this.models.list.add(name);
this.models.list.sort();
this.models.list.setCurrent(name);
}
}
private void exportModel()
{
List<String> mobs = new ArrayList<String>();
for (Entry<ResourceLocation, EntityEntry> entry : ForgeRegistries.ENTITIES.getEntries())
{
Class<? extends Entity> clazz = entry.getValue().getEntityClass();
while (clazz != null)
{
if (clazz == EntityLivingBase.class)
{
mobs.add(entry.getKey().toString());
break;
}
else
{
clazz = (Class<? extends Entity>) clazz.getSuperclass();
}
}
}
Collections.sort(mobs);
GuiModal.addFullModal(this, () ->
{
GuiListModal modal = new GuiListModal(this.mc, IKey.lang("blockbuster.gui.me.models.pick"), this::exportModel);
return modal.addValues(mobs);
});
}
private void exportModel(String name)
{
if (name.isEmpty())
{
return;
}
try
{
Entity entity = EntityList.createEntityByIDFromName(new ResourceLocation(name), this.mc.world);
Render render = Minecraft.getMinecraft().getRenderManager().getEntityRenderObject(entity);
ModelExporter exporter = new ModelExporter((EntityLivingBase) entity, (RenderLivingBase) render);
Model model = exporter.exportModel(name);
name = name.replaceAll(":", "_");
model.fillInMissing();
this.panel.setModel(name, model, new ModelLazyLoaderJSON(new StreamEntry("", 0)));
}
catch (Exception e)
{
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.str(I18n.format("blockbuster.gui.me.models.error", e.getMessage()))));
e.printStackTrace();
}
}
private void openFolder()
{
GuiUtils.openFolder(new File(ClientProxy.configFile, "models/" + this.panel.modelName).getAbsolutePath());
}
@Override
public void draw(GuiContext context)
{
this.area.draw(0xaa000000);
super.draw(context);
}
} | 7,069 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelOptions.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/tabs/GuiModelOptions.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.GuiModelEditorPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiThreeElement;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiTwoElement;
import mchorse.mclib.client.gui.framework.elements.GuiScrollElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Direction;
import net.minecraft.client.Minecraft;
public class GuiModelOptions extends GuiModelEditorTab
{
/* Main properties */
private GuiTextElement name;
private GuiTwoElement texture;
private GuiTrackpadElement extrudeMaxFactor;
private GuiTrackpadElement extrudeInwards;
private GuiThreeElement scale;
private GuiTrackpadElement scaleGui;
private GuiButtonElement defaultTexture;
private GuiTextElement skins;
private GuiToggleElement providesObj;
private GuiToggleElement providesMtl;
private GuiToggleElement legacyObj;
public GuiModelOptions(Minecraft mc, GuiModelEditorPanel panel)
{
super(mc, panel);
/* Main properties */
GuiScrollElement element = new GuiScrollElement(mc);
this.name = new GuiTextElement(mc, 120, (str) -> this.panel.model.name = str);
this.texture = new GuiTwoElement(mc, (value) ->
{
this.panel.model.texture[0] = value[0].intValue();
this.panel.model.texture[1] = value[1].intValue();
this.panel.rebuildModel();
});
this.texture.setLimit(1, 8196, true);
this.extrudeMaxFactor = new GuiTrackpadElement(mc, (value) ->
{
this.panel.model.extrudeMaxFactor = value.intValue();
this.panel.rebuildModel();
});
this.extrudeMaxFactor.tooltip(IKey.lang("blockbuster.gui.me.options.extrude_max_factor"));
this.extrudeMaxFactor.integer().limit(1);
this.extrudeInwards = new GuiTrackpadElement(mc, (value) ->
{
this.panel.model.extrudeInwards = value.intValue();
this.panel.rebuildModel();
});
this.extrudeInwards.tooltip(IKey.lang("blockbuster.gui.me.options.extrude_inwards"));
this.extrudeInwards.integer().limit(1);
this.scale = new GuiThreeElement(mc, (value) ->
{
this.panel.model.scale[0] = value[0].floatValue();
this.panel.model.scale[1] = value[1].floatValue();
this.panel.model.scale[2] = value[2].floatValue();
});
this.scaleGui = new GuiTrackpadElement(mc, (value) ->
{
this.panel.model.scaleGui = value.floatValue();
this.panel.dirty();
});
this.scaleGui.tooltip(IKey.lang("blockbuster.gui.me.options.scale_gui"));
this.defaultTexture = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.me.options.default_texture"), (b) ->
{
this.panel.pickTexture(this.panel.model.defaultTexture, (rl) ->
{
this.panel.model.defaultTexture = rl;
this.panel.dirty();
});
});
this.skins = new GuiTextElement(mc, 120, (str) ->
{
this.panel.model.skins = str;
this.panel.dirty();
});
this.providesObj = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.options.provides_obj"), false, (b) ->
{
this.panel.model.providesObj = b.isToggled();
this.panel.rebuildModel();
});
this.providesMtl = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.options.provides_mtl"), false, (b) ->
{
this.panel.model.providesMtl = b.isToggled();
this.panel.rebuildModel();
});
this.legacyObj = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.me.options.legacy_obj"), false, (b) ->
{
this.panel.model.legacyObj = b.isToggled();
this.panel.rebuildModel();
});
this.legacyObj.tooltip(IKey.lang("blockbuster.gui.me.options.legacy_obj_tooltip"), Direction.TOP);
element.flex().relative(this).wh(1F, 1F).column(5).vertical().stretch().scroll().padding(10).height(20);
element.add(Elements.label(IKey.lang("blockbuster.gui.me.options.name")), this.name);
element.add(Elements.label(IKey.lang("blockbuster.gui.me.options.texture")), this.texture);
element.add(Elements.label(IKey.lang("blockbuster.gui.me.options.extrusion")), this.extrudeMaxFactor, this.extrudeInwards);
element.add(Elements.label(IKey.lang("blockbuster.gui.me.options.scale")), this.scale, this.scaleGui, this.defaultTexture);
element.add(Elements.label(IKey.lang("blockbuster.gui.me.options.skins")), this.skins, this.providesObj, this.providesMtl, this.legacyObj);
this.add(element);
}
public void fillData(Model model)
{
this.name.setText(model.name);
this.texture.setValues(model.texture[0], model.texture[1]);
this.extrudeMaxFactor.setValue(model.extrudeMaxFactor);
this.extrudeInwards.setValue(model.extrudeInwards);
this.scale.setValues(model.scale[0], model.scale[1], model.scale[2]);
this.scaleGui.setValue(model.scaleGui);
this.skins.setText(model.skins);
this.providesObj.toggled(model.providesObj);
this.providesMtl.toggled(model.providesMtl);
this.legacyObj.toggled(model.legacyObj);
}
@Override
public void draw(GuiContext context)
{
this.area.draw(0xaa000000);
super.draw(context);
}
} | 6,104 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelPoses.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/tabs/GuiModelPoses.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.GuiModelEditorPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiTwoElement;
import mchorse.blockbuster.client.gui.utils.GuiShapeKeysEditor;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.context.GuiContextMenu;
import mchorse.mclib.client.gui.framework.elements.context.GuiSimpleContextMenu;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiListModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiMessageModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
import java.util.function.Consumer;
public class GuiModelPoses extends GuiModelEditorTab
{
private GuiIconElement addPose;
private GuiIconElement removePose;
private GuiIconElement copyPose;
private GuiIconElement applyPose;
private GuiStringListElement posesList;
private GuiShapeKeysEditor shapeKeys;
private GuiTwoElement hitbox;
private GuiElement bottom;
private String pose;
public static GuiSimpleContextMenu createCopyPasteMenu(Runnable copy, Consumer<ModelPose> paste)
{
GuiSimpleContextMenu menu = new GuiSimpleContextMenu(Minecraft.getMinecraft());
ModelPose pose = null;
try
{
NBTTagCompound tag = JsonToNBT.getTagFromJson(GuiScreen.getClipboardString());
ModelPose loaded = new ModelPose();
loaded.fromNBT(tag);
pose = loaded;
}
catch (Exception e)
{}
menu.action(Icons.COPY, IKey.lang("blockbuster.gui.me.poses.context.copy"), copy);
if (pose != null)
{
final ModelPose innerPose = pose;
menu.action(Icons.PASTE, IKey.lang("blockbuster.gui.me.poses.context.paste"), () -> paste.accept(innerPose));
}
return menu;
}
public GuiModelPoses(Minecraft mc, GuiModelEditorPanel panel)
{
super(mc, panel);
this.title = IKey.lang("blockbuster.gui.me.poses.title");
this.hitbox = new GuiTwoElement(mc, (values) ->
{
this.panel.pose.size[0] = values[0].floatValue();
this.panel.pose.size[1] = values[1].floatValue();
this.panel.dirty();
});
/* Buttons */
this.addPose = new GuiIconElement(mc, Icons.ADD, (b) -> this.addPose());
this.removePose = new GuiIconElement(mc, Icons.REMOVE, (b) -> this.removePose());
this.copyPose = new GuiIconElement(mc, Icons.COPY, (b) -> this.copyPose());
this.copyPose.tooltip(IKey.lang("blockbuster.gui.me.poses.copy_pose_tooltip"));
this.applyPose = new GuiIconElement(mc, Icons.PASTE, (b) -> this.applyPose());
this.applyPose.tooltip(IKey.lang("blockbuster.gui.me.poses.apply_pose_tooltip"));
GuiElement sidebar = Elements.row(mc, 0, 0, 20, this.addPose, this.removePose, this.copyPose, this.applyPose);
this.bottom = new GuiElement(mc);
sidebar.flex().relative(this).x(1F).h(20).anchorX(1F).row(0).resize();
this.bottom.flex().relative(this).y(1F).w(1F).anchorY(1F).column(5).vertical().stretch().height(20).padding(10);
this.posesList = new GuiStringListElement(mc, (str) -> this.setPose(str.get(0)));
this.posesList.flex().relative(this).y(20).w(1F).hTo(bottom.area);
this.posesList.context(() ->
{
GuiSimpleContextMenu menu = createCopyPasteMenu(this::copyCurrentPose, this::pastePose);
menu.action(Icons.EDIT, IKey.lang("blockbuster.gui.me.poses.context.rename"), this::renamePose);
return menu;
});
this.shapeKeys = new GuiShapeKeysEditor(mc, () -> this.panel.model);
this.shapeKeys.flex().relative(this.posesList).y(1F, 10).x(10).w(1F, -20).hTo(this.hitbox.area, -27);
this.bottom.add(Elements.label(IKey.lang("blockbuster.gui.me.poses.hitbox")), this.hitbox);
this.add(sidebar, this.bottom, this.posesList);
}
private void copyCurrentPose()
{
GuiScreen.setClipboardString(this.panel.pose.toNBT(new NBTTagCompound()).toString());
}
private void pastePose(ModelPose pose)
{
GuiModal.addFullModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(mc, IKey.lang("blockbuster.gui.me.poses.paste_pose"), (text) ->
{
this.addPose(text, pose);
});
String base = "pasted_pose";
String name = base;
int index = 1;
while (this.panel.model.poses.containsKey(name))
{
name = base + "_" + (index++);
}
return modal.setValue(name);
});
}
private void renamePose()
{
GuiModal.addFullModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(mc, IKey.lang("blockbuster.gui.me.poses.rename_pose"), this::renamePose);
return modal.setValue(this.pose);
});
}
private void renamePose(String name)
{
if (!this.panel.model.poses.containsKey(name))
{
this.panel.model.poses.put(name, this.panel.model.poses.remove(this.pose));
this.posesList.remove(this.pose);
this.posesList.add(name);
this.posesList.sort();
this.panel.setPose(name, true);
this.panel.dirty();
}
}
private void addPose()
{
GuiModal.addFullModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(mc, IKey.lang("blockbuster.gui.me.poses.new_pose"), this::addPose);
return modal.setValue(this.pose);
});
}
private void addPose(String pose)
{
this.addPose(pose, this.panel.pose == null ? new ModelPose() : this.panel.pose.copy());
}
private void addPose(String name, ModelPose pose)
{
if (!this.panel.model.poses.containsKey(name))
{
this.panel.model.poses.put(name, pose);
this.posesList.add(name);
this.posesList.sort();
this.panel.setPose(name, true);
this.panel.dirty();
}
}
private void removePose()
{
if (Model.REQUIRED_POSES.contains(this.pose))
{
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.lang("blockbuster.gui.me.poses.standard")));
}
else
{
this.panel.model.poses.remove(this.pose);
String newPose = null;
int index = this.posesList.getIndex();
int size = this.posesList.getList().size();
if (index > 0 && size > 1)
{
newPose = this.posesList.getList().get(this.posesList.getIndex() - 1);
}
else if (index == 0 && size > 1)
{
newPose = this.posesList.getList().get(1);
}
if (newPose == null)
{
newPose = this.panel.model.poses.keySet().iterator().next();
}
this.posesList.remove(this.pose);
this.setPose(newPose);
this.panel.dirty();
}
}
private void copyPose()
{
GuiModal.addFullModal(this, () ->
{
GuiListModal modal = new GuiListModal(this.mc, IKey.lang("blockbuster.gui.me.poses.copy_pose"), this::copyPose);
return modal.addValues(this.panel.model.poses.keySet());
});
}
private void copyPose(String text)
{
ModelPose pose = this.panel.model.poses.get(text);
if (pose == null)
{
return;
}
this.panel.transform.copy(pose.limbs.get(this.panel.limb.name));
this.panel.dirty();
}
private void applyPose()
{
GuiModal.addFullModal(this, () ->
{
GuiListModal modal = new GuiListModal(this.mc, IKey.lang("blockbuster.gui.me.poses.apply_pose"), null).callback(this::copyPose);
modal.list.getList().remove(0);
modal.list.multi();
modal.addValues(this.panel.model.poses.keySet());
modal.list.selectAll();
modal.list.toggleIndex(modal.list.getList().indexOf(this.pose));
return modal;
});
}
private void copyPose(List<String> poses)
{
ModelPose pose = this.panel.model.poses.get(this.pose);
if (pose == null)
{
return;
}
ModelTransform current = pose.limbs.get(this.panel.limb.name);
if (current == null || poses.isEmpty())
{
return;
}
for (String name : poses)
{
ModelPose target = this.panel.model.poses.get(name);
if (target != null)
{
ModelTransform transform = target.limbs.get(this.panel.limb.name);
if (transform != null)
{
transform.copy(current);
}
}
}
this.panel.dirty();
}
public void setPose(String str)
{
this.pose = str;
this.panel.setPose(str);
this.fillPoseData();
}
public void setCurrent(String pose, boolean scroll)
{
this.pose = pose;
if (scroll)
{
this.posesList.setCurrentScroll(pose);
}
else
{
this.posesList.setCurrent(pose);
}
this.fillPoseData();
}
public void fillData(Model model)
{
this.posesList.clear();
this.posesList.add(model.poses.keySet());
this.posesList.sort();
}
public void fillPoseData()
{
this.hitbox.setValues(this.panel.pose.size[0], this.panel.pose.size[1]);
boolean isVisible = !this.panel.model.shapes.isEmpty();
if (isVisible)
{
this.shapeKeys.fillData(this.panel.pose.shapes);
if (!this.shapeKeys.hasParent())
{
this.add(this.shapeKeys);
this.posesList.flex().h(0.4F);
}
}
else
{
this.shapeKeys.removeFromParent();
this.posesList.flex().hTo(this.bottom.area);
}
this.resize();
}
@Override
public void draw(GuiContext context)
{
this.area.draw(0xaa000000);
super.draw(context);
}
} | 11,298 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiAnchorModal.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/tabs/GuiAnchorModal.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiThreeElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
import javax.vecmath.Vector3f;
import java.util.function.Consumer;
public class GuiAnchorModal extends GuiModal
{
public Consumer<Vector3f> callback;
public GuiThreeElement vector;
public GuiButtonElement confirm;
public GuiAnchorModal(Minecraft mc, IKey label, Consumer<Vector3f> callback)
{
super(mc, label);
this.callback = callback;
this.vector = new GuiThreeElement(mc, null);
this.vector.setLimit(0, 1, false);
this.vector.a.increment(0.1).values(0.05, 0.01, 0.1);
this.vector.b.increment(0.1).values(0.05, 0.01, 0.1);
this.vector.c.increment(0.1).values(0.05, 0.01, 0.1);
this.vector.flex().relative(this).set(10, 0, 0, 20).y(1, -55).w(1, -20);
this.confirm = new GuiButtonElement(mc, IKey.lang("mclib.gui.ok"), (b) -> this.send());
this.bar.add(this.confirm);
this.add(this.vector);
}
public void send()
{
this.removeFromParent();
if (this.callback != null)
{
this.callback.accept(new Vector3f((float) this.vector.a.value, (float) this.vector.b.value, (float) this.vector.c.value));
}
}
@Override
public boolean keyTyped(GuiContext context)
{
if (super.keyTyped(context))
{
return true;
}
if (context.keyCode == Keyboard.KEY_RETURN)
{
this.confirm.clickItself(context);
return true;
}
return false;
}
} | 2,001 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelEditorTab.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_editor/tabs/GuiModelEditorTab.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_editor.tabs;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.GuiModelEditorPanel;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public abstract class GuiModelEditorTab extends GuiElement
{
protected IKey title = IKey.EMPTY;
protected GuiModelEditorPanel panel;
public GuiModelEditorTab(Minecraft mc, GuiModelEditorPanel panel)
{
super(mc);
this.panel = panel;
}
public GuiModelEditorPanel getPanel()
{
return this.panel;
}
@Override
public void draw(GuiContext context)
{
this.drawLabels();
super.draw(context);
}
protected void drawLabels()
{
if (this.title != null)
{
this.font.drawStringWithShadow(this.title.get(), this.area.x + 4, this.area.y + 6, 0xeeeeee);
}
}
} | 1,068 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelBlockList.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_block/GuiModelBlockList.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_block;
import mchorse.blockbuster.client.gui.dashboard.panels.GuiBlockList;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import java.util.List;
import java.util.function.Consumer;
/**
* Model block list
*/
public class GuiModelBlockList extends GuiBlockList<TileEntityModel>
{
public GuiModelBlockList(Minecraft mc, IKey title, Consumer<List<TileEntityModel>> callback)
{
super(mc, title, callback);
}
@Override
public boolean addBlock(BlockPos pos)
{
TileEntity tile = this.mc.world.getTileEntity(pos);
if (tile instanceof TileEntityModel)
{
this.list.add((TileEntityModel) tile);
this.scroll.setSize(this.list.size());
this.scroll.clamp();
return true;
}
return false;
}
@Override
protected void drawElementPart(TileEntityModel element, int i, int x, int y, boolean hover, boolean selected)
{
GuiContext context = GuiBase.getCurrent();
int h = this.scroll.scrollItemSize;
if (!element.morph.isEmpty())
{
int mny = MathHelper.clamp(y, this.scroll.y, this.scroll.ey());
int mxy = MathHelper.clamp(y + 20, this.scroll.y, this.scroll.ey());
if (mxy - mny > 0)
{
GuiDraw.scissor(x, mny, this.scroll.w, mxy - mny, context);
element.morph.get().renderOnScreen(this.mc.player, x + this.scroll.w - 16, y + 30, 20, 1);
GuiDraw.unscissor(context);
}
}
BlockPos pos = element.getPos();
String label = String.format("(%s, %s, %s)", pos.getX(), pos.getY(), pos.getZ());
this.font.drawStringWithShadow(label, x + 10, y + 6, hover ? 16777120 : 0xffffff);
Gui.drawRect(x, y + h - 1, x + this.area.w, y + h, 0x88181818);
}
} | 2,405 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiModelBlockPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/model_block/GuiModelBlockPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.model_block;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.gui.GuiImmersiveEditor;
import mchorse.blockbuster.client.gui.GuiImmersiveMorphMenu;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanel;
import mchorse.blockbuster.common.BlockbusterPermissions;
import mchorse.blockbuster.common.block.BlockModel;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.PacketModifyModelBlock;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTransformations;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.permissions.PermissionCategory;
import mchorse.mclib.utils.ColorUtils;
import mchorse.mclib.utils.Direction;
import mchorse.mclib.utils.MatrixUtils.RotationOrder;
import mchorse.mclib.utils.MatrixUtils.Transformation;
import mchorse.mclib.utils.OpHelper;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiNestedEdit;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
public class GuiModelBlockPanel extends GuiBlockbusterPanel
{
public static final List<BlockPos> lastBlocks = new ArrayList<BlockPos>();
private TileEntityModel model;
private GuiTrackpadElement yaw;
private GuiTrackpadElement pitch;
private GuiTrackpadElement body;
private GuiModelBlockTransformations trans;
private GuiNestedEdit pickMorph;
private GuiCirculateElement order;
private GuiToggleElement shadow;
private GuiToggleElement global;
private GuiToggleElement enabled;
private GuiToggleElement excludeResetPlayback;
private GuiToggleElement renderLast;
private GuiToggleElement renderAlways;
private GuiToggleElement enableBlockHitbox;
private GuiTrackpadElement lightLevel;
private GuiModelBlockList list;
private GuiElement subChildren;
private GuiSlotElement[] slots = new GuiSlotElement[6];
private Map<BlockPos, TileEntityModel> old = new HashMap<BlockPos, TileEntityModel>();
private AbstractMorph morph;
private boolean opened;
/**
* Try adding a block position, if it doesn't exist in list already
*/
public static void tryAddingBlock(BlockPos pos)
{
for (BlockPos stored : lastBlocks)
{
if (pos.equals(stored))
{
return;
}
}
lastBlocks.add(pos);
}
public GuiModelBlockPanel(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
this.subChildren = new GuiElement(mc).noCulling();
this.subChildren.setVisible(false);
this.add(this.subChildren);
/* Transformations */
this.trans = new GuiModelBlockTransformations(mc);
this.trans.flex().relative(this).x(0.5F, 42).y(1F, -10).wh(250, 70).anchor(0.5F, 1F);
this.subChildren.add(this.trans);
/* Entity angles */
this.subChildren.add(this.yaw = new GuiTrackpadElement(mc, (value) -> this.model.getSettings().setRotateYawHead(value.floatValue())));
this.yaw.tooltip(IKey.lang("blockbuster.gui.model_block.yaw"));
this.subChildren.add(this.pitch = new GuiTrackpadElement(mc, (value) -> this.model.getSettings().setRotatePitch(value.floatValue())));
this.pitch.tooltip(IKey.lang("blockbuster.gui.model_block.pitch"));
this.subChildren.add(this.body = new GuiTrackpadElement(mc, (value) -> this.model.getSettings().setRotateBody(value.floatValue())));
this.body.tooltip(IKey.lang("blockbuster.gui.model_block.body"));
this.yaw.flex().set(-85, 0, 80, 20).relative(this.trans);
this.pitch.flex().set(0, 25, 80, 20).relative(this.yaw.resizer());
this.body.flex().set(0, 25, 80, 20).relative(this.pitch.resizer());
this.subChildren.add(this.order = new GuiCirculateElement(mc, (b) ->
{
int index = 0;
if (this.order.getValue() == 0)
{
index = 5;
}
this.model.getSettings().setOrder(RotationOrder.values()[index]);
}));
this.order.addLabel(IKey.str("ZYX"));
this.order.addLabel(IKey.str("XYZ"));
this.order.flex().relative(this.trans.rx).set(40, -22, 40, 20);
/* Buttons */
GuiElement column = new GuiElement(mc);
column.flex().relative(this).w(120).column(5).vertical().stretch().height(20).padding(10);
this.pickMorph = new GuiNestedEdit(mc, (editing) ->
{
if (Blockbuster.immersiveModelBlock.get())
{
GuiImmersiveEditor editor = ClientProxy.panels.showImmersiveEditor(editing, this.model.morph.get());
editor.morphs.updateCallback = this::updateMorphEditor;
editor.morphs.beforeRender = this::beforeEditorRender;
editor.morphs.afterRender = this::afterEditorRender;
editor.onClose = this::afterEditorClose;
/* Avoid update. */
this.morph = this.model.morph.get();
this.model.morph.setDirect(MorphUtils.copy(this.morph));
}
else
{
ClientProxy.panels.addMorphs(this, editing, this.model.morph.get());
}
});
GuiButtonElement look = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.model_block.look"), (button) ->
{
this.model.getSettings().setRy(180 - this.mc.player.rotationYaw);
this.fillData();
});
this.shadow = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.shadow"), false, (button) -> this.model.getSettings().setShadow(button.isToggled()));
this.global = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.global"), false, (button) -> this.model.getSettings().setGlobal(button.isToggled()));
this.global.tooltip(IKey.lang("blockbuster.gui.model_block.global_tooltip"), Direction.BOTTOM);
this.enabled = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.enabled"), false, (button) -> this.model.getSettings().setEnabled(button.isToggled()));
this.enabled.tooltip(IKey.lang("blockbuster.gui.model_block.enabled_tooltip"), Direction.BOTTOM);
this.excludeResetPlayback = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.exlude_reset_playback"), false, (button) -> this.model.getSettings().setExcludeResetPlayback(button.isToggled()));
this.excludeResetPlayback.tooltip(IKey.lang("blockbuster.gui.model_block.exlude_reset_playback_tooltip"), Direction.BOTTOM);
this.renderLast = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.render_last"), false, (button) -> this.model.getSettings().setRenderLast(button.isToggled()));
this.renderLast.tooltip(IKey.lang("blockbuster.gui.model_block.render_last_tooltip"), Direction.BOTTOM);
this.renderAlways = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.render_always"), false, (button) -> this.model.getSettings().setRenderAlways(button.isToggled()));
this.renderAlways.tooltip(IKey.lang("blockbuster.gui.model_block.render_always_tooltip"), Direction.BOTTOM);
this.enableBlockHitbox = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.model_block.enable_hitbox"), false, (b) -> this.model.getSettings().setEnableBlockHitbox(b.isToggled()));
this.enableBlockHitbox.tooltip(IKey.lang("blockbuster.gui.model_block.enable_hitbox_tooltip"), Direction.BOTTOM);
this.lightLevel = new GuiTrackpadElement(mc, (value) ->
{
this.model.getSettings().setLightValue(value.intValue());
this.model.getWorld().setBlockState(this.model.getPos(), this.model.getWorld().getBlockState(this.model.getPos()).withProperty(BlockModel.LIGHT, this.model.getSettings().getLightValue()) , 2);
});
this.lightLevel.integer().limit(0, 15);
this.lightLevel.tooltip(IKey.lang("blockbuster.gui.model_block.light_level_tooltip"));
column.add(this.pickMorph, look, this.shadow, this.global, this.enabled, this.excludeResetPlayback, this.renderLast, this.renderAlways, this.enableBlockHitbox, Elements.label(IKey.lang("blockbuster.gui.model_block.light_level")), this.lightLevel);
this.subChildren.add(column);
/* Model blocks */
this.list = new GuiModelBlockList(mc, IKey.lang("blockbuster.gui.model_block.title"), (tile) -> this.setModelBlock(tile.get(0)));
this.list.flex().relative(this.flex()).set(0, 0, 120, 0).h(1F).x(1F, -120);
this.add(this.list);
GuiIconElement toggle = new GuiIconElement(mc, Icons.BLOCK, (b) -> this.list.toggleVisible());
toggle.flex().set(0, 2, 24, 24).relative(this).x(1F, -28);
this.add(toggle);
/* Inventory */
for (int i = 0; i < this.slots.length; i++)
{
final int slot = i;
this.slots[i] = new GuiSlotElement(mc, i, (stack) -> this.pickItem(stack, slot));
this.slots[i].flex().relative(this.area).anchor(0.5F, 0.5F);
this.subChildren.add(this.slots[i]);
}
this.slots[0].flex().x(0.5F - 0.125F).y(0.5F, -15);
this.slots[1].flex().x(0.5F - 0.125F).y(0.5F, 15);
this.slots[2].flex().x(0.5F + 0.125F).y(0.5F, 45);
this.slots[3].flex().x(0.5F + 0.125F).y(0.5F, 15);
this.slots[4].flex().x(0.5F + 0.125F).y(0.5F, -15);
this.slots[5].flex().x(0.5F + 0.125F).y(0.5F, -45);
}
public boolean isOpened()
{
return this.opened;
}
/**
* @param tileEntityModel
* @return true if the provided tileEntityModel reference matches the reference of the selected model.
*/
public boolean isSelected(TileEntityModel tileEntityModel)
{
return this.model == tileEntityModel;
}
@Override
public PermissionCategory getRequiredPermission()
{
return BlockbusterPermissions.editModelBlock;
}
@Override
public boolean needsBackground()
{
return false;
}
private void pickItem(ItemStack stack, int slot)
{
this.model.getSettings().setSlot(stack, slot);
this.model.updateEntity();
}
private void setMorph(AbstractMorph morph)
{
if (this.model != null)
{
if (Blockbuster.immersiveModelBlock.get())
{
this.morph = morph;
}
else
{
this.model.morph.setDirect(morph);
}
}
this.pickMorph.setMorph(morph);
}
private void updateMorphEditor(GuiImmersiveMorphMenu menu)
{
if (this.model == null)
{
return;
}
TileEntity te = this.model.getWorld().getTileEntity(this.model.getPos());
if (te != this.model)
{
if (te instanceof TileEntityModel)
{
this.setModelBlock((TileEntityModel) te);
}
}
menu.target = this.model.entity;
}
private void beforeEditorRender(GuiContext context)
{
GlStateManager.pushMatrix();
ClientProxy.modelRenderer.transform(this.model);
}
private void afterEditorRender(GuiContext context)
{
GlStateManager.popMatrix();
}
private void afterEditorClose(GuiImmersiveEditor editor)
{
this.model.morph.setDirect(this.morph);
}
@Override
public void appear()
{
super.appear();
ClientProxy.panels.picker(this::setMorph);
}
@Override
public void open()
{
opened = true;
this.updateList();
/* Resetting the current model block, if it was removed from the world */
if (this.model != null && this.mc.world.getTileEntity(this.model.getPos()) == null)
{
this.setModelBlock(null);
}
}
@Override
public void close()
{
this.save(null);
opened = false;
}
public void save(TileEntityModel model)
{
this.save(model, false);
}
public void save(TileEntityModel model, boolean force)
{
if (!OpHelper.isPlayerOp())
{
return;
}
if (!force)
{
if (this.model == null || this.model == model)
{
return;
}
if (model != null && this.model.getPos().equals(model.getPos()))
{
return;
}
}
if (ClientProxy.panels.morphs.hasParent())
{
ClientProxy.panels.morphs.finish();
ClientProxy.panels.morphs.removeFromParent();
}
Dispatcher.sendToServer(new PacketModifyModelBlock(this.model.getPos(), this.model));
if (Blockbuster.modelBlockRestore.get())
{
this.old.put(this.model.getPos(), this.model);
}
}
public GuiModelBlockPanel openModelBlock(TileEntityModel model)
{
if (model != null && Blockbuster.modelBlockRestore.get() && this.old.containsKey(model.getPos()))
{
TileEntityModel old = this.old.get(model.getPos());
model.copyData(old, false);
}
tryAddingBlock(model.getPos());
this.updateList();
this.list.setVisible(false);
return this.setModelBlock(model);
}
public GuiModelBlockPanel setModelBlock(TileEntityModel model)
{
this.save(model);
this.list.setCurrent(model);
this.subChildren.setVisible(model != null);
this.model = model;
this.fillData();
return this;
}
private void updateList()
{
this.list.clear();
for (BlockPos pos : lastBlocks)
{
this.list.addBlock(pos);
}
this.list.setCurrent(this.model);
}
private void fillData()
{
if (this.model != null)
{
this.yaw.setValue(this.model.getSettings().getRotateYawHead());
this.pitch.setValue(this.model.getSettings().getRotatePitch());
this.body.setValue(this.model.getSettings().getRotateBody());
this.trans.set(this.model);
this.pickMorph.setMorph(this.model.morph.get());
int orderIndex = this.model.getSettings().getOrder().ordinal();
if (orderIndex == 5)
{
this.order.setValue(0);
}
else if (orderIndex == 0)
{
this.order.setValue(1);
}
this.shadow.toggled(this.model.getSettings().isShadow());
this.global.toggled(this.model.getSettings().isGlobal());
this.enabled.toggled(this.model.getSettings().isEnabled());
this.excludeResetPlayback.toggled(this.model.getSettings().isExcludeResetPlayback());
this.renderLast.toggled(this.model.getSettings().isRenderLast());
this.renderAlways.toggled(this.model.getSettings().isRenderAlways());
this.enableBlockHitbox.toggled(this.model.getSettings().isBlockHitbox());
this.lightLevel.setValue(this.model.getSettings().getLightValue());
for (int i = 0; i < this.slots.length; i++)
{
this.slots[i].setStack(this.model.getSettings().getSlots()[i]);
}
}
}
@Override
public void draw(GuiContext context)
{
if (this.model != null)
{
AbstractMorph morph = this.model.morph.get();
if (morph != null)
{
int x = this.area.mx();
int y = this.area.y + 30;
int w = Math.max(this.font.getStringWidth(morph.name), this.font.getStringWidth(morph.getDisplayName()));
Gui.drawRect(x - w / 2 - 3, y - 20, x + w / 2 + 3, y, ColorUtils.HALF_BLACK);
this.drawCenteredString(this.font, morph.getDisplayName(), x, y - this.font.FONT_HEIGHT * 2, 0xffffff);
this.drawCenteredString(this.font, morph.name, x, y - this.font.FONT_HEIGHT, 0xcccccc);
}
}
if (this.subChildren.isVisible())
{
this.drawString(this.font, I18n.format("blockbuster.gui.model_block.entity"), this.yaw.area.x + 2, this.yaw.area.y - 12, 0xffffff);
}
else if (this.model == null)
{
this.drawCenteredString(this.font, I18n.format("blockbuster.gui.model_block.not_selected"), this.area.mx(), this.area.my() - 6, 0xffffff);
}
super.draw(context);
}
public static class GuiModelBlockTransformations extends GuiTransformations
{
public TileEntityModel model;
public GuiModelBlockTransformations(Minecraft mc)
{
super(mc);
this.one.callback = (toggle) ->
{
boolean one = toggle.isToggled();
this.model.getSettings().setUniform(one);
this.updateScaleFields();
if (!one)
{
this.sy.setValueAndNotify(this.sx.value);
this.sz.setValueAndNotify(this.sx.value);
}
};
}
public void set(TileEntityModel model)
{
this.model = model;
if (model != null)
{
this.fillT(model.getSettings().getX(), model.getSettings().getY(), model.getSettings().getZ());
this.fillS(model.getSettings().getSx(), model.getSettings().getSy(), model.getSettings().getSz());
this.fillR(model.getSettings().getRx(), model.getSettings().getRy(), model.getSettings().getRz());
this.one.toggled(model.getSettings().isUniform());
this.updateScaleFields();
}
}
@Override
public void setT(double x, double y, double z)
{
this.model.getSettings().setX((float) x);
this.model.getSettings().setY((float) y);
this.model.getSettings().setZ((float) z);
}
@Override
public void setS(double x, double y, double z)
{
this.model.getSettings().setSx((float) x);
this.model.getSettings().setSy((float) y);
this.model.getSettings().setSz((float) z);
}
@Override
public void setR(double x, double y, double z)
{
this.model.getSettings().setRx((float) x);
this.model.getSettings().setRy((float) y);
this.model.getSettings().setRz((float) z);
}
@Override
protected void localTranslate(double x, double y, double z)
{
this.model.getSettings().addTranslation(x, y, z, GuiStaticTransformOrientation.getOrientation());
this.fillT(this.model.getSettings().getX(), this.model.getSettings().getY(), this.model.getSettings().getZ());
}
@Override
protected void prepareRotation(Matrix4f mat)
{
RotationOrder order = RotationOrder.valueOf(this.model.getSettings().getOrder().toString());
float[] rot = new float[] {(float) this.rx.value, (float) this.ry.value, (float) this.rz.value};
Matrix4f trans = new Matrix4f();
trans.setIdentity();
trans.set(Transformation.getRotationMatrix(order.thirdIndex, rot[order.thirdIndex]));
mat.mul(trans);
trans.set(Transformation.getRotationMatrix(order.secondIndex, rot[order.secondIndex]));
mat.mul(trans);
trans.set(Transformation.getRotationMatrix(order.firstIndex, rot[order.firstIndex]));
mat.mul(trans);
}
@Override
protected void postRotation(Transformation transform)
{
Vector3f result = transform.getRotation(RotationOrder.valueOf(this.model.getSettings().getOrder().toString()), new Vector3f((float) this.rx.value, (float) this.ry.value, (float) this.rz.value));
this.rx.setValueAndNotify(result.x);
this.ry.setValueAndNotify(result.y);
this.rz.setValueAndNotify(result.z);
}
}
} | 21,518 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockScheme.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/BedrockScheme.java | package mchorse.blockbuster.client.particles;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentEmitterInitialize;
import mchorse.blockbuster.client.particles.components.IComponentEmitterUpdate;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.components.IComponentParticleMorphRender;
import mchorse.blockbuster.client.particles.components.IComponentParticleRender;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentInitialSpeed;
import mchorse.mclib.math.Variable;
import mchorse.mclib.math.molang.MolangParser;
import net.minecraft.util.ResourceLocation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class BedrockScheme
{
public static final ResourceLocation DEFAULT_TEXTURE = new ResourceLocation(Blockbuster.MOD_ID, "textures/default_particles.png");
public static final Gson JSON_PARSER = new GsonBuilder()
.registerTypeAdapter(BedrockScheme.class, new BedrockSchemeJsonAdapter())
.create();
/* Particles identifier */
public String identifier = "";
/* Particle description */
public BedrockMaterial material = BedrockMaterial.OPAQUE;
public ResourceLocation texture = DEFAULT_TEXTURE;
/* Particle's curves */
public Map<String, BedrockCurve> curves = new HashMap<String, BedrockCurve>();
/* Particle's components */
public List<BedrockComponentBase> components = new ArrayList<BedrockComponentBase>();
public List<IComponentEmitterInitialize> emitterInitializes;
public List<IComponentEmitterUpdate> emitterUpdates;
public List<IComponentParticleInitialize> particleInitializes;
public List<IComponentParticleUpdate> particleUpdates;
public List<IComponentParticleRender> particleRender;
public List<IComponentParticleMorphRender> particleMorphRender;
private boolean factory;
/* MoLang integration */
public MolangParser parser;
public static BedrockScheme parse(String json)
{
return JSON_PARSER.fromJson(json, BedrockScheme.class);
}
public static BedrockScheme parse(JsonElement json)
{
return JSON_PARSER.fromJson(json, BedrockScheme.class);
}
public static JsonElement toJson(BedrockScheme scheme)
{
return JSON_PARSER.toJsonTree(scheme);
}
/**
* Probably it's very expensive, but it's much easier than implementing copy methods
* to every component in the particle system...
*/
public static BedrockScheme dupe(BedrockScheme scheme)
{
return parse(toJson(scheme));
}
public BedrockScheme()
{
this.parser = new MolangParser();
/* Default variables */
this.parser.register(new Variable("variable.particle_age", 0));
this.parser.register(new Variable("variable.particle_lifetime", 0));
this.parser.register(new Variable("variable.particle_random_1", 0));
this.parser.register(new Variable("variable.particle_random_2", 0));
this.parser.register(new Variable("variable.particle_random_3", 0));
this.parser.register(new Variable("variable.particle_random_4", 0));
this.parser.register(new Variable("variable.particle_speed.length", 0));
this.parser.register(new Variable("variable.particle_speed.x", 0));
this.parser.register(new Variable("variable.particle_speed.y", 0));
this.parser.register(new Variable("variable.particle_speed.z", 0));
this.parser.register(new Variable("variable.particle_pos.x", 0));
this.parser.register(new Variable("variable.particle_pos.y", 0));
this.parser.register(new Variable("variable.particle_pos.z", 0));
this.parser.register(new Variable("variable.particle_pos.distance", 0));
this.parser.register(new Variable("variable.particle_bounces", 0));
this.parser.register(new Variable("variable.emitter_age", 0));
this.parser.register(new Variable("variable.emitter_lifetime", 0));
this.parser.register(new Variable("variable.emitter_random_1", 0));
this.parser.register(new Variable("variable.emitter_random_2", 0));
this.parser.register(new Variable("variable.emitter_random_3", 0));
this.parser.register(new Variable("variable.emitter_random_4", 0));
}
public BedrockScheme factory(boolean factory)
{
this.factory = factory;
return this;
}
public boolean isFactory()
{
return this.factory;
}
public void setup()
{
this.getOrCreate(BedrockComponentInitialSpeed.class);
this.emitterInitializes = this.getComponents(IComponentEmitterInitialize.class);
this.emitterUpdates = this.getComponents(IComponentEmitterUpdate.class);
this.particleInitializes = this.getComponents(IComponentParticleInitialize.class);
this.particleUpdates = this.getComponents(IComponentParticleUpdate.class);
this.particleRender = this.getComponents(IComponentParticleRender.class);
this.particleMorphRender = this.getComponents(IComponentParticleMorphRender.class);
/* Link variables with curves */
for (Map.Entry<String, BedrockCurve> entry : this.curves.entrySet())
{
entry.getValue().variable = this.parser.variables.get(entry.getKey());
}
}
public <T extends IComponentBase> List<T> getComponents(Class<T> clazz)
{
List<T> list = new ArrayList<T>();
for (BedrockComponentBase component : this.components)
{
if (clazz.isAssignableFrom(component.getClass()))
{
list.add((T) component);
}
}
if (list.size() > 1)
{
Collections.sort(list, Comparator.comparingInt(IComponentBase::getSortingIndex));
}
return list;
}
public <T extends BedrockComponentBase> T get(Class<T> clazz)
{
for (BedrockComponentBase component : this.components)
{
if (clazz.isAssignableFrom(component.getClass()))
{
return (T) component;
}
}
return null;
}
public <T extends BedrockComponentBase> T getExact(Class<T> clazz)
{
for (BedrockComponentBase component : this.components)
{
if (clazz.equals(component.getClass()))
{
return (T) component;
}
}
return null;
}
public <T extends BedrockComponentBase> T add(Class<T> clazz)
{
T result = null;
try
{
result = clazz.getConstructor().newInstance();
this.components.add(result);
this.setup();
}
catch (Exception e)
{}
return result;
}
/**
* This method gets the component using isAssignableFrom() method. It can also get sub-classes
* @param clazz target class
* @param <T>
* @return the component object
*/
public <T extends BedrockComponentBase> T getOrCreate(Class<T> clazz)
{
return this.getOrCreate(clazz, clazz);
}
/**
* This method gets the component by its exact class and no sub-classes.
* @param clazz target class
* @param <T>
* @return the component object
*/
public <T extends BedrockComponentBase> T getOrCreateExact(Class<T> clazz)
{
return this.getOrCreateExact(clazz, clazz);
}
/**
* This method gets the component using isAssignableFrom() method. It can also get sub-classes. If clazz hasn't been found it will add the subclass parameter.
* @param clazz target class
* @param clazz alternative class too add in case target class doesnt exist
* @param <T>
* @return the component object
*/
public <T extends BedrockComponentBase> T getOrCreate(Class<T> clazz, Class subclass)
{
T result = this.get(clazz);
if (result == null)
{
result = (T) this.add(subclass);
}
return result;
}
public <T extends BedrockComponentBase> T getOrCreateExact(Class<T> clazz, Class subclass)
{
T result = this.getExact(clazz);
if (result == null)
{
result = (T) this.add(subclass);
}
return result;
}
public <T extends BedrockComponentBase> T remove(Class<T> clazz)
{
Iterator<BedrockComponentBase> it = this.components.iterator();
while (it.hasNext())
{
BedrockComponentBase component = it.next();
if (clazz.isAssignableFrom(component.getClass()))
{
it.remove();
return (T) component;
}
}
return null;
}
public <T extends BedrockComponentBase> T replace(Class<T> clazz, Class subclass)
{
this.remove(clazz);
return (T) this.add(subclass);
}
/**
* Update curve values
*/
public void updateCurves()
{
for (BedrockCurve curve : this.curves.values())
{
if (curve.variable != null)
{
curve.variable.set(curve.compute());
}
}
}
} | 9,754 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockCurveType.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/BedrockCurveType.java | package mchorse.blockbuster.client.particles;
public enum BedrockCurveType
{
LINEAR("linear"), HERMITE("catmull_rom");
public final String id;
public static BedrockCurveType fromString(String type)
{
for (BedrockCurveType t : values())
{
if (t.id.equals(type))
{
return t;
}
}
return LINEAR;
}
private BedrockCurveType(String id)
{
this.id = id;
}
} | 478 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockSchemeJsonAdapter.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/BedrockSchemeJsonAdapter.java | package mchorse.blockbuster.client.particles;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceBillboard;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceLighting;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceTinting;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionAppearance;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionTinting;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentParticleMorph;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentExpireInBlocks;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentExpireNotInBlocks;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentKillPlane;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentParticleLifetime;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetimeExpression;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetimeLooping;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetimeOnce;
import mchorse.blockbuster.client.particles.components.meta.BedrockComponentInitialization;
import mchorse.blockbuster.client.particles.components.meta.BedrockComponentLocalSpace;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentInitialSpeed;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentInitialSpin;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotionCollision;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotionDynamic;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotionParametric;
import mchorse.blockbuster.client.particles.components.rate.BedrockComponentRateInstant;
import mchorse.blockbuster.client.particles.components.rate.BedrockComponentRateSteady;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeBox;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeDisc;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeEntityAABB;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapePoint;
import mchorse.blockbuster.client.particles.components.shape.BedrockComponentShapeSphere;
import mchorse.mclib.math.Operation;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.utils.resources.RLUtils;
import java.lang.reflect.Type;
import java.util.Map;
public class BedrockSchemeJsonAdapter implements JsonDeserializer<BedrockScheme>, JsonSerializer<BedrockScheme>
{
public BiMap<String, Class<? extends BedrockComponentBase>> components = HashBiMap.create();
public static boolean isEmpty(JsonElement element)
{
if (element.isJsonArray())
{
return element.getAsJsonArray().size() == 0;
}
else if (element.isJsonObject())
{
return element.getAsJsonObject().size() == 0;
}
else if (element.isJsonPrimitive())
{
JsonPrimitive primitive = element.getAsJsonPrimitive();
if (primitive.isString())
{
return primitive.getAsString().isEmpty();
}
else if (primitive.isNumber())
{
return Operation.equals(primitive.getAsDouble(), 0);
}
}
return element.isJsonNull();
}
public BedrockSchemeJsonAdapter()
{
/* Meta components */
this.components.put("minecraft:emitter_local_space", BedrockComponentLocalSpace.class);
this.components.put("minecraft:emitter_initialization", BedrockComponentInitialization.class);
/* Rate */
this.components.put("minecraft:emitter_rate_instant", BedrockComponentRateInstant.class);
this.components.put("minecraft:emitter_rate_steady", BedrockComponentRateSteady.class);
/* Lifetime emitter */
this.components.put("minecraft:emitter_lifetime_looping", BedrockComponentLifetimeLooping.class);
this.components.put("minecraft:emitter_lifetime_once", BedrockComponentLifetimeOnce.class);
this.components.put("minecraft:emitter_lifetime_expression", BedrockComponentLifetimeExpression.class);
/* Shapes */
this.components.put("minecraft:emitter_shape_disc", BedrockComponentShapeDisc.class);
this.components.put("minecraft:emitter_shape_box", BedrockComponentShapeBox.class);
this.components.put("minecraft:emitter_shape_entity_aabb", BedrockComponentShapeEntityAABB.class);
this.components.put("minecraft:emitter_shape_point", BedrockComponentShapePoint.class);
this.components.put("minecraft:emitter_shape_sphere", BedrockComponentShapeSphere.class);
/* Lifetime particle */
this.components.put("minecraft:particle_lifetime_expression", BedrockComponentParticleLifetime.class);
this.components.put("minecraft:particle_expire_if_in_blocks", BedrockComponentExpireInBlocks.class);
this.components.put("minecraft:particle_expire_if_not_in_blocks", BedrockComponentExpireNotInBlocks.class);
this.components.put("minecraft:particle_kill_plane", BedrockComponentKillPlane.class);
/* Appearance */
this.components.put("minecraft:particle_appearance_billboard", BedrockComponentAppearanceBillboard.class);
this.components.put("minecraft:particle_appearance_lighting", BedrockComponentAppearanceLighting.class);
this.components.put("minecraft:particle_appearance_tinting", BedrockComponentAppearanceTinting.class);
this.components.put("blockbuster:particle_collision_appearance", BedrockComponentCollisionAppearance.class);
this.components.put("blockbuster:particle_collision_tinting", BedrockComponentCollisionTinting.class);
this.components.put("blockbuster:particle_morph", BedrockComponentParticleMorph.class);
/* Motion & Rotation */
this.components.put("minecraft:particle_initial_speed", BedrockComponentInitialSpeed.class);
this.components.put("minecraft:particle_initial_spin", BedrockComponentInitialSpin.class);
this.components.put("minecraft:particle_motion_collision", BedrockComponentMotionCollision.class);
this.components.put("minecraft:particle_motion_dynamic", BedrockComponentMotionDynamic.class);
this.components.put("minecraft:particle_motion_parametric", BedrockComponentMotionParametric.class);
}
@Override
public BedrockScheme deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
BedrockScheme scheme = new BedrockScheme();
if (!json.isJsonObject())
{
throw new JsonParseException("The root element of Bedrock particle should be an object!");
}
/* Skip format_version check to avoid breaking semi-compatible particles */
JsonObject root = json.getAsJsonObject();
try
{
this.parseEffect(scheme, this.getObject(root, "particle_effect", "No particle_effect was found..."));
}
catch (MolangException e)
{
throw new JsonParseException("Couldn't parse some MoLang expression!", e);
}
scheme.setup();
return scheme;
}
private void parseEffect(BedrockScheme scheme, JsonObject effect) throws JsonParseException, MolangException
{
this.parseDescription(scheme, this.getObject(effect, "description", "No particle_effect.description was found..."));
if (effect.has("curves"))
{
JsonElement curves = effect.get("curves");
if (curves.isJsonObject())
{
this.parseCurves(scheme, curves.getAsJsonObject());
}
}
this.parseComponents(scheme, this.getObject(effect, "components", "No particle_effect.components was found..."));
}
/**
* Parse description object (which contains ID of the particle, material type and texture)
*/
private void parseDescription(BedrockScheme scheme, JsonObject description) throws JsonParseException
{
if (description.has("identifier"))
{
scheme.identifier = description.get("identifier").getAsString();
}
JsonObject parameters = this.getObject(description, "basic_render_parameters", "No particle_effect.basic_render_parameters was found...");
if (parameters.has("material"))
{
scheme.material = BedrockMaterial.fromString(parameters.get("material").getAsString());
}
if (parameters.has("texture"))
{
String texture = parameters.get("texture").getAsString();
if (!texture.equals("textures/particle/particles"))
{
scheme.texture = RLUtils.create(texture);
}
}
}
/**
* Parse curves object
*/
private void parseCurves(BedrockScheme scheme, JsonObject curves) throws MolangException
{
for (Map.Entry<String, JsonElement> entry : curves.entrySet())
{
JsonElement element = entry.getValue();
if (element.isJsonObject())
{
BedrockCurve curve = new BedrockCurve();
curve.fromJson(element.getAsJsonObject(), scheme.parser);
scheme.curves.put(entry.getKey(), curve);
}
}
}
private void parseComponents(BedrockScheme scheme, JsonObject components) throws MolangException
{
for (Map.Entry<String, JsonElement> entry : components.entrySet())
{
String key = entry.getKey();
if (this.components.containsKey(key))
{
BedrockComponentBase component = null;
try
{
component = this.components.get(key).getConstructor().newInstance();
}
catch (Exception e)
{}
if (component != null)
{
component.fromJson(entry.getValue(), scheme.parser);
scheme.components.add(component);
}
else
{
System.out.println("Failed to parse given component " + key + " in " + scheme.identifier + "!");
}
}
}
}
private JsonObject getObject(JsonObject object, String key, String message) throws JsonParseException
{
/* Skip format_version check to avoid breaking semi-compatible particles */
if (!object.has(key) && !object.get(key).isJsonObject())
{
throw new JsonParseException(message);
}
return object.get(key).getAsJsonObject();
}
/**
* Turn given bedrock scheme into JSON
*/
@Override
public JsonElement serialize(BedrockScheme src, Type typeOfSrc, JsonSerializationContext context)
{
JsonObject object = new JsonObject();
JsonObject effect = new JsonObject();
object.addProperty("format_version", "1.10.0");
object.add("particle_effect", effect);
this.addDescription(effect, src);
this.addCurves(effect, src);
this.addComponents(effect, src);
return object;
}
private void addDescription(JsonObject effect, BedrockScheme scheme)
{
JsonObject desc = new JsonObject();
JsonObject render = new JsonObject();
effect.add("description", desc);
desc.addProperty("identifier", scheme.identifier);
desc.add("basic_render_parameters", render);
render.addProperty("material", scheme.material.id);
render.addProperty("texture", "textures/particle/particles");
if (scheme.texture != null && !scheme.texture.equals(BedrockScheme.DEFAULT_TEXTURE))
{
render.addProperty("texture", scheme.texture.toString());
}
}
private void addCurves(JsonObject effect, BedrockScheme scheme)
{
JsonObject curves = new JsonObject();
effect.add("curves", curves);
for (Map.Entry<String, BedrockCurve> entry : scheme.curves.entrySet())
{
curves.add(entry.getKey(), entry.getValue().toJson());
}
}
private void addComponents(JsonObject effect, BedrockScheme scheme)
{
JsonObject components = new JsonObject();
effect.add("components", components);
for (BedrockComponentBase component : scheme.components)
{
JsonElement element = component.toJson();
if (this.isEmpty(element) && !component.canBeEmpty())
{
continue;
}
components.add(this.components.inverse().get(component.getClass()), element);
}
}
} | 13,666 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockLibrary.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/BedrockLibrary.java | package mchorse.blockbuster.client.particles;
import mchorse.mclib.utils.JsonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class BedrockLibrary
{
public static long lastUpdate;
public Map<String, BedrockScheme> presets = new HashMap<String, BedrockScheme>();
public Map<String, BedrockScheme> factory = new HashMap<String, BedrockScheme>();
public File folder;
public BedrockLibrary(File folder)
{
this.folder = folder;
this.folder.mkdirs();
/* Load factory (default) presets */
this.storeFactory("default_fire");
this.storeFactory("default_magic");
this.storeFactory("default_rain");
this.storeFactory("default_snow");
}
public File file(String name)
{
return new File(this.folder, name + ".json");
}
public boolean hasEffect(String name)
{
return this.file(name).isFile();
}
public void reload()
{
this.presets.clear();
this.presets.putAll(this.factory);
for (File file : this.folder.listFiles())
{
if (file.isFile() && file.getName().endsWith(".json"))
{
this.storeScheme(file);
}
}
}
public BedrockScheme load(String name)
{
BedrockScheme scheme = this.loadScheme(this.file(name));
if (scheme != null)
{
return scheme;
}
return this.loadFactory(name);
}
private void storeScheme(File file)
{
BedrockScheme scheme = this.loadScheme(file);
if (scheme != null)
{
String name = file.getName();
this.presets.put(name.substring(0, name.indexOf(".json")), scheme);
}
}
/**
* Load a scheme from a file
*/
public BedrockScheme loadScheme(File file)
{
if (!file.exists())
{
return null;
}
try
{
return BedrockScheme.parse(FileUtils.readFileToString(file, StandardCharsets.UTF_8));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private void storeFactory(String name)
{
BedrockScheme scheme = this.loadFactory(name);
if (scheme != null)
{
this.factory.put(name, scheme);
}
}
/**
* Load a scheme from Blockbuster's zip
*/
public BedrockScheme loadFactory(String name)
{
try
{
return BedrockScheme.parse(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("assets/blockbuster/particles/" + name + ".json"), StandardCharsets.UTF_8)).factory(true);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public void save(String filename, BedrockScheme scheme)
{
String json = JsonUtils.jsonToPretty(BedrockScheme.toJson(scheme));
File file = this.file(filename);
try
{
FileUtils.writeStringToFile(file, json, StandardCharsets.UTF_8);
}
catch (Exception e)
{}
this.storeScheme(file);
lastUpdate = System.currentTimeMillis();
}
} | 3,400 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockCurve.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/BedrockCurve.java | package mchorse.blockbuster.client.particles;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.mclib.math.Variable;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.Interpolations;
import mchorse.mclib.utils.MathUtils;
public class BedrockCurve
{
public BedrockCurveType type = BedrockCurveType.LINEAR;
public MolangExpression[] nodes = {MolangParser.ZERO, MolangParser.ONE, MolangParser.ZERO};
public MolangExpression input;
public MolangExpression range;
public Variable variable;
public double compute()
{
return this.computeCurve(this.input.get() / this.range.get());
}
private double computeCurve(double factor)
{
int length = this.nodes.length;
if (length == 0)
{
return 0;
}
else if (length == 1)
{
return this.nodes[0].get();
}
if (factor < 0)
{
factor = -(1 + factor);
}
factor = MathUtils.clamp(factor, 0, 1);
if (this.type == BedrockCurveType.HERMITE)
{
if (length <= 3)
{
return this.nodes[length - 2].get();
}
factor *= (length - 3);
int index = (int) factor + 1;
MolangExpression beforeFirst = this.getNode(index - 1);
MolangExpression first = this.getNode(index);
MolangExpression next = this.getNode(index + 1);
MolangExpression afterNext = this.getNode(index + 2);
return Interpolations.cubicHermite(beforeFirst.get(), first.get(), next.get(), afterNext.get(), factor % 1);
}
factor *= length - 1;
int index = (int) factor;
MolangExpression first = this.getNode(index);
MolangExpression next = this.getNode(index + 1);
return Interpolations.lerp(first.get(), next.get(), factor % 1);
}
private MolangExpression getNode(int index)
{
if (index < 0)
{
return this.nodes[0];
}
else if (index >= this.nodes.length)
{
return this.nodes[this.nodes.length - 1];
}
return this.nodes[index];
}
public void fromJson(JsonObject object, MolangParser parser) throws MolangException
{
if (object.has("type"))
{
this.type = BedrockCurveType.fromString(object.get("type").getAsString());
}
if (object.has("input"))
{
this.input = parser.parseJson(object.get("input"));
}
if (object.has("horizontal_range"))
{
this.range = parser.parseJson(object.get("horizontal_range"));
}
if (object.has("nodes"))
{
JsonArray nodes = object.getAsJsonArray("nodes");
MolangExpression[] result = new MolangExpression[nodes.size()];
for (int i = 0, c = result.length; i < c; i ++)
{
result[i] = parser.parseJson(nodes.get(i));
}
this.nodes = result;
}
}
public JsonElement toJson()
{
JsonObject curve = new JsonObject();
JsonArray nodes = new JsonArray();
curve.addProperty("type", this.type.id);
curve.add("nodes", nodes);
curve.add("input", this.input.toJson());
curve.add("horizontal_range", this.range.toJson());
for (MolangExpression expression : this.nodes)
{
nodes.add(expression.toJson());
}
return curve;
}
} | 3,738 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockMaterial.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/BedrockMaterial.java | package mchorse.blockbuster.client.particles;
import net.minecraft.client.renderer.GlStateManager;
import org.lwjgl.opengl.GL11;
public enum BedrockMaterial
{
OPAQUE("particles_opaque"), ALPHA("particles_alpha"), BLEND("particles_blend"), ADDITIVE("particles_add");
public final String id;
public static BedrockMaterial fromString(String material)
{
for (BedrockMaterial mat : values())
{
if (mat.id.equals(material))
{
return mat;
}
}
return OPAQUE;
}
private BedrockMaterial(String id)
{
this.id = id;
}
public void beginGL()
{
switch (this)
{
case OPAQUE:
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0F);
GlStateManager.disableBlend();
GlStateManager.enableAlpha();
break;
case ALPHA:
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.1F);
GlStateManager.disableBlend();
GlStateManager.enableAlpha();
break;
case BLEND:
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.0F);
GlStateManager.enableBlend();
GlStateManager.enableAlpha();
break;
case ADDITIVE:
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.0F);
GlStateManager.enableBlend();
GlStateManager.enableAlpha();
break;
}
}
public void endGL()
{
switch (this)
{
case OPAQUE:
case ALPHA:
case BLEND:
case ADDITIVE:
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.disableBlend();
GlStateManager.enableAlpha();
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.1F);
break;
}
}
} | 2,524 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockEmitter.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/emitter/BedrockEmitter.java | package mchorse.blockbuster.client.particles.emitter;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.*;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceBillboard;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionAppearance;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionTinting;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentParticleMorph;
import mchorse.blockbuster.client.particles.components.meta.BedrockComponentInitialization;
import mchorse.blockbuster.client.particles.components.rate.BedrockComponentRateSteady;
import mchorse.blockbuster.client.textures.GifTexture;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.math.IValue;
import mchorse.mclib.math.Variable;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.Interpolations;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import javax.vecmath.Matrix3f;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import java.util.*;
public class BedrockEmitter
{
public BedrockScheme scheme;
public List<BedrockParticle> particles = new ArrayList<BedrockParticle>();
public List<BedrockParticle> splitParticles = new ArrayList<BedrockParticle>();
public Map<String, IValue> variables;
public Map<String, Double> initialValues = new HashMap<String, Double>();
public EntityLivingBase target;
public World world;
public boolean lit;
public boolean added;
public int sanityTicks;
public boolean running = true;
private BedrockParticle guiParticle;
/* Intermediate values */
public Vector3d lastGlobal = new Vector3d();
public Vector3d prevGlobal = new Vector3d();
public Matrix3f rotation = new Matrix3f(1,0,0,0,1,0,0,0,1);
public Matrix3f prevRotation = new Matrix3f(1,0,0,0,1,0,0,0,1);
public Vector3f angularVelocity = new Vector3f();
/**
* Translation of immediate bodypart
*/
public Vector3d translation = new Vector3d();
/* Runtime properties */
public int age;
public int lifetime;
public double spawnedParticles;
public boolean playing = true;
public float random1 = (float) Math.random();
public float random2 = (float) Math.random();
public float random3 = (float) Math.random();
public float random4 = (float) Math.random();
private BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos();
public double[] scale = {1,1,1};
/* Camera properties */
public int perspective;
public float cYaw;
public float cPitch;
public double cX;
public double cY;
public double cZ;
/* Cached variable references to avoid hash look ups */
private Variable varAge;
private Variable varLifetime;
private Variable varRandom1;
private Variable varRandom2;
private Variable varRandom3;
private Variable varRandom4;
/* Exclusive Blockbuster variables */
private Variable varSpeedABS;
private Variable varSpeedX;
private Variable varSpeedY;
private Variable varSpeedZ;
private Variable varPosX;
private Variable varPosY;
private Variable varPosZ;
private Variable varPosDistance;
private Variable varBounces;
private Variable varEmitterAge;
private Variable varEmitterLifetime;
private Variable varEmitterRandom1;
private Variable varEmitterRandom2;
private Variable varEmitterRandom3;
private Variable varEmitterRandom4;
public boolean isFinished()
{
return !this.running && this.particles.isEmpty();
}
public double getDistanceSq()
{
this.setupCameraProperties(0F);
double dx = this.cX - this.lastGlobal.x;
double dy = this.cY - this.lastGlobal.y;
double dz = this.cZ - this.lastGlobal.z;
return dx * dx + dy * dy + dz * dz;
}
public double getAge()
{
return this.getAge(0);
}
public double getAge(float partialTicks)
{
return (this.age + partialTicks) / 20.0;
}
public boolean isMorphParticle()
{
BedrockComponentParticleMorph morphComponent = this.scheme.getOrCreate(BedrockComponentParticleMorph.class);
return morphComponent.enabled;
}
public void setTarget(EntityLivingBase target)
{
this.target = target;
this.world = target == null ? null : target.world;
}
public void setScheme(BedrockScheme scheme)
{
this.setScheme(scheme, null);
}
public void setScheme(BedrockScheme scheme, Map<String, String> variables)
{
this.scheme = scheme;
if (this.scheme == null)
{
return;
}
if (variables != null)
{
this.parseVariables(variables);
}
this.lit = true;
this.stop();
this.start();
this.setupVariables();
this.setEmitterVariables(0);
}
/* Variable related code */
public void setupVariables()
{
this.varAge = this.scheme.parser.variables.get("variable.particle_age");
this.varLifetime = this.scheme.parser.variables.get("variable.particle_lifetime");
this.varRandom1 = this.scheme.parser.variables.get("variable.particle_random_1");
this.varRandom2 = this.scheme.parser.variables.get("variable.particle_random_2");
this.varRandom3 = this.scheme.parser.variables.get("variable.particle_random_3");
this.varRandom4 = this.scheme.parser.variables.get("variable.particle_random_4");
this.varSpeedABS = this.scheme.parser.variables.get("variable.particle_speed.length");
this.varSpeedX = this.scheme.parser.variables.get("variable.particle_speed.x");
this.varSpeedY = this.scheme.parser.variables.get("variable.particle_speed.y");
this.varSpeedZ = this.scheme.parser.variables.get("variable.particle_speed.z");
this.varPosX = this.scheme.parser.variables.get("variable.particle_pos.x");
this.varPosY = this.scheme.parser.variables.get("variable.particle_pos.y");
this.varPosZ = this.scheme.parser.variables.get("variable.particle_pos.z");
this.varPosDistance = this.scheme.parser.variables.get("variable.particle_pos.distance");
this.varBounces = this.scheme.parser.variables.get("variable.particle_bounces");
this.varEmitterAge = this.scheme.parser.variables.get("variable.emitter_age");
this.varEmitterLifetime = this.scheme.parser.variables.get("variable.emitter_lifetime");
this.varEmitterRandom1 = this.scheme.parser.variables.get("variable.emitter_random_1");
this.varEmitterRandom2 = this.scheme.parser.variables.get("variable.emitter_random_2");
this.varEmitterRandom3 = this.scheme.parser.variables.get("variable.emitter_random_3");
this.varEmitterRandom4 = this.scheme.parser.variables.get("variable.emitter_random_4");
}
public void setParticleVariables(BedrockParticle particle, float partialTicks)
{
if (this.varAge != null) this.varAge.set(particle.getAge(partialTicks));
if (this.varLifetime != null) this.varLifetime.set(particle.lifetime / 20.0);
if (this.varRandom1 != null) this.varRandom1.set(particle.random1);
if (this.varRandom2 != null) this.varRandom2.set(particle.random2);
if (this.varRandom3 != null) this.varRandom3.set(particle.random3);
if (this.varRandom4 != null) this.varRandom4.set(particle.random4);
Vector3d relativePos = new Vector3d(particle.getGlobalPosition(this));
relativePos.sub(this.lastGlobal);
if (this.varPosDistance != null) this.varPosDistance.set(relativePos.length());
if (this.varPosX != null) this.varPosX.set(relativePos.x);
if (this.varPosY != null) this.varPosY.set(relativePos.y);
if (this.varPosZ != null) this.varPosZ.set(relativePos.z);
if (this.varSpeedABS != null) this.varSpeedABS.set(particle.speed.length());
if (this.varSpeedX != null) this.varSpeedX.set(particle.speed.x);
if (this.varSpeedY != null) this.varSpeedY.set(particle.speed.y);
if (this.varSpeedZ != null) this.varSpeedZ.set(particle.speed.z);
if (this.varBounces != null) this.varBounces.set(particle.bounces);
this.scheme.updateCurves();
BedrockComponentInitialization component = this.scheme.get(BedrockComponentInitialization.class);
if (component != null)
{
component.particleUpdate.get();
}
}
public void setEmitterVariables(float partialTicks)
{
for (Map.Entry<String, Double> entry : this.initialValues.entrySet())
{
Variable var = this.scheme.parser.variables.get(entry.getKey());
if (var != null)
{
var.set(entry.getValue());
}
}
if (this.varEmitterAge != null) this.varEmitterAge.set(this.getAge(partialTicks));
if (this.varEmitterLifetime != null) this.varEmitterLifetime.set(this.lifetime / 20.0);
if (this.varEmitterRandom1 != null) this.varEmitterRandom1.set(this.random1);
if (this.varEmitterRandom2 != null) this.varEmitterRandom2.set(this.random2);
if (this.varEmitterRandom3 != null) this.varEmitterRandom3.set(this.random3);
if (this.varEmitterRandom4 != null) this.varEmitterRandom4.set(this.random4);
this.scheme.updateCurves();
}
public void parseVariables(Map<String, String> variables)
{
this.variables = new HashMap<String, IValue>();
for (Map.Entry<String, String> entry : variables.entrySet())
{
this.parseVariable(entry.getKey(), entry.getValue());
}
}
public void parseVariable(String name, String expression)
{
try
{
this.variables.put(name, this.scheme.parser.parse(expression));
}
catch (Exception e)
{}
}
public void replaceVariables()
{
if (this.variables == null)
{
return;
}
for (Map.Entry<String, IValue> entry : this.variables.entrySet())
{
Variable var = this.scheme.parser.variables.get(entry.getKey());
if (var != null)
{
var.set(entry.getValue().get().doubleValue());
}
}
}
public void start()
{
if (this.playing)
{
return;
}
this.age = 0;
this.spawnedParticles = 0;
this.playing = true;
for (IComponentEmitterInitialize component : this.scheme.emitterInitializes)
{
component.apply(this);
}
}
public void stop()
{
if (!this.playing)
{
return;
}
this.spawnedParticles = 0;
this.playing = false;
this.random1 = (float) Math.random();
this.random2 = (float) Math.random();
this.random3 = (float) Math.random();
this.random4 = (float) Math.random();
}
/**
* Update this current emitter
*/
public void update()
{
if (this.scheme == null)
{
return;
}
this.setEmitterVariables(0);
for (IComponentEmitterUpdate component : this.scheme.emitterUpdates)
{
component.update(this);
}
this.setEmitterVariables(0);
this.updateParticles();
this.age += 1;
this.sanityTicks += 1;
}
/**
* Update all particles
*/
private void updateParticles()
{
Iterator<BedrockParticle> it = this.particles.iterator();
while (it.hasNext())
{
BedrockParticle particle = it.next();
this.updateParticle(particle);
if (particle.dead)
{
it.remove();
}
}
if (!this.splitParticles.isEmpty())
{
this.particles.addAll(this.splitParticles);
this.splitParticles.clear();
}
}
/**
* Update a single particle
*/
private void updateParticle(BedrockParticle particle)
{
particle.update(this);
this.setParticleVariables(particle, 0);
for (IComponentParticleUpdate component : this.scheme.particleUpdates)
{
component.update(this, particle);
}
}
/**
* Spawn a particle
*/
public void spawnParticle()
{
if (!this.running)
{
return;
}
this.particles.add(this.createParticle(false));
}
/**
* Create a new particle
*/
public BedrockParticle createParticle(boolean forceRelative)
{
BedrockParticle particle = new BedrockParticle();
this.setParticleVariables(particle, 0);
particle.setupMatrix(this);
for (IComponentParticleInitialize component : this.scheme.particleInitializes)
{
component.apply(this, particle);
}
if (particle.relativePosition && !particle.relativeRotation)
{
Vector3f vec = new Vector3f(particle.position);
particle.matrix.transform(vec);
particle.position.x = vec.x;
particle.position.y = vec.y;
particle.position.z = vec.z;
}
if (!(particle.relativePosition && particle.relativeRotation))
{
particle.position.add(this.lastGlobal);
particle.initialPosition.add(this.lastGlobal);
}
particle.prevPosition.set(particle.position);
particle.rotation = particle.initialRotation;
particle.prevRotation = particle.rotation;
return particle;
}
/**
* Render the particle on screen
*/
public void renderOnScreen(int x, int y, float scale)
{
if (this.scheme == null)
{
return;
}
BedrockComponentParticleMorph particleMorphComponent = this.scheme.getOrCreate(BedrockComponentParticleMorph.class);
float partialTicks = Minecraft.getMinecraft().getRenderPartialTicks();
List<IComponentParticleRender> listParticle = this.scheme.getComponents(IComponentParticleRender.class);
List<IComponentParticleMorphRender> listMorph = this.scheme.getComponents(IComponentParticleMorphRender.class);
Matrix3f rotation = this.rotation;
this.rotation = new Matrix3f();
if (!listParticle.isEmpty() && (!this.isMorphParticle() || particleMorphComponent.renderTexture))
{
Minecraft.getMinecraft().renderEngine.bindTexture(this.scheme.texture);
this.scheme.material.beginGL();
GlStateManager.disableCull();
if (this.guiParticle == null || this.guiParticle.dead)
{
this.guiParticle = this.createParticle(true);
}
this.rotation.setIdentity();
this.guiParticle.update(this);
this.setEmitterVariables(partialTicks);
this.setParticleVariables(this.guiParticle, partialTicks);
for (IComponentParticleRender render : listParticle)
{
render.renderOnScreen(this.guiParticle, x, y, scale, partialTicks);
}
this.scheme.material.endGL();
GlStateManager.enableCull();
}
if (!listMorph.isEmpty() && this.isMorphParticle())
{
if (this.guiParticle == null || this.guiParticle.dead)
{
this.guiParticle = this.createParticle(true);
}
this.rotation.setIdentity();
this.guiParticle.update(this);
this.setEmitterVariables(partialTicks);
this.setParticleVariables(this.guiParticle, partialTicks);
for (IComponentParticleMorphRender render : listMorph)
{
render.renderOnScreen(this.guiParticle, x, y, scale, partialTicks);
}
}
this.rotation = rotation;
}
/**
* Render all the particles in this particle emitter
*/
public void render(float partialTicks)
{
if (this.scheme == null)
{
return;
}
this.setupCameraProperties(partialTicks);
BedrockComponentParticleMorph particleMorphComponent = this.scheme.getOrCreate(BedrockComponentParticleMorph.class);
List<IComponentParticleRender> renders = this.scheme.particleRender;
List<IComponentParticleMorphRender> morphRenders = this.scheme.particleMorphRender;
boolean morphRendering = this.isMorphParticle();
boolean particleRendering = !morphRendering || particleMorphComponent.renderTexture;
/* particle rendering */
if (particleRendering)
{
this.setupOpenGL(partialTicks);
for (IComponentParticleRender component : renders)
{
component.preRender(this, partialTicks);
}
if (!this.particles.isEmpty())
{
this.depthSorting();
this.renderParticles(this.scheme.texture, renders, false, partialTicks);
BedrockComponentCollisionAppearance collisionAppearance = this.scheme.getOrCreate(BedrockComponentCollisionAppearance.class);
/* rendering the collided particles with an extra component */
if (collisionAppearance != null && collisionAppearance.texture != null)
{
this.renderParticles(collisionAppearance.texture, renders, true, partialTicks);
}
}
for (IComponentParticleRender component : renders)
{
component.postRender(this, partialTicks);
}
this.endOpenGL();
}
/* Morph rendering */
if (morphRendering)
{
for (IComponentParticleMorphRender component : morphRenders)
{
component.preRender(this, partialTicks);
}
if (!this.particles.isEmpty())
{
//only depth sort either in particle rendering or morph rendering
if (!particleRendering)
{
this.depthSorting();
}
this.renderParticles(morphRenders, false, partialTicks);
/*BedrockComponentCollisionParticleMorph collisionComponent = this.scheme.getOrCreate(BedrockComponentCollisionParticleMorph.class);
if (collisionComponent != null && collisionComponent.morph != null)
{
this.renderParticles(morphRenders, true, partialTicks);
}*/
}
for (IComponentParticleMorphRender component : morphRenders)
{
if (component.getClass() == BedrockComponentRateSteady.class)
{
if (!particleRendering)
{
//only spawn particles either in particles or in morph rendering
component.postRender(this, partialTicks);
}
}
else
{
component.postRender(this, partialTicks);
}
}
}
}
/**
* This method renders the particles using morphs
* @param renderComponents
* @param collided
* @param partialTicks
*/
private void renderParticles(List<? extends IComponentParticleMorphRender> renderComponents, boolean collided, float partialTicks)
{
BufferBuilder builder = Tessellator.getInstance().getBuffer();
for (BedrockParticle particle : this.particles)
{
this.setEmitterVariables(partialTicks);
this.setParticleVariables(particle, partialTicks);
for (IComponentRenderBase component : renderComponents)
{
component.render(this, particle, builder, partialTicks);
}
}
}
/**
* This method renders the particles using the default bedrock billboards
* @param texture Ressource location of the texture to render
* @param renderComponents
* @param collided
* @param partialTicks
*/
private void renderParticles(ResourceLocation texture, List<? extends IComponentParticleRender> renderComponents, boolean collided, float partialTicks)
{
BufferBuilder builder = Tessellator.getInstance().getBuffer();
GifTexture.bindTexture(texture, this.age, partialTicks);
builder.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_LMAP_COLOR);
for (BedrockParticle particle : this.particles)
{
boolean collisionStuff = particle.isCollisionTexture(this) || particle.isCollisionTinting(this);
if (collisionStuff != collided)
{
continue;
}
this.setEmitterVariables(partialTicks);
this.setParticleVariables(particle, partialTicks);
for (IComponentRenderBase component : renderComponents)
{
/* if collisionTexture or collisionTinting is true - means that those options are enabled
* therefore the old Billboardappearance should not be called
* because collisionAppearance.class is rendering
*/
if (!(collisionStuff && component.getClass() == BedrockComponentAppearanceBillboard.class))
{
component.render(this, particle, builder, partialTicks);
}
}
}
Tessellator.getInstance().draw();
}
private void setupOpenGL(float partialTicks)
{
this.scheme.material.beginGL();
if (!GuiModelRenderer.isRendering())
{
Entity camera = Minecraft.getMinecraft().getRenderViewEntity();
double playerX = camera.prevPosX + (camera.posX - camera.prevPosX) * (double) partialTicks;
double playerY = camera.prevPosY + (camera.posY - camera.prevPosY) * (double) partialTicks;
double playerZ = camera.prevPosZ + (camera.posZ - camera.prevPosZ) * (double) partialTicks;
BufferBuilder builder = Tessellator.getInstance().getBuffer();
builder.setTranslation(-playerX, -playerY, -playerZ);
GlStateManager.disableCull();
GlStateManager.enableTexture2D();
}
}
private void endOpenGL()
{
if (!GuiModelRenderer.isRendering())
{
Tessellator.getInstance().getBuffer().setTranslation(0, 0, 0);
}
this.scheme.material.endGL();
}
private void depthSorting()
{
if (Blockbuster.snowstormDepthSorting.get())
{
this.particles.sort((a, b) ->
{
double ad = a.getDistanceSq(this);
double bd = b.getDistanceSq(this);
if (ad < bd)
{
return 1;
}
else if (ad > bd)
{
return -1;
}
return 0;
});
}
}
public void setupCameraProperties(float partialTicks)
{
if (this.world != null)
{
Entity camera = Minecraft.getMinecraft().getRenderViewEntity();
this.perspective = Minecraft.getMinecraft().gameSettings.thirdPersonView;
this.cYaw = 180 - Interpolations.lerp(camera.prevRotationYaw, camera.rotationYaw, partialTicks);
this.cPitch = 180 - Interpolations.lerp(camera.prevRotationPitch, camera.rotationPitch, partialTicks);
this.cX = Interpolations.lerp(camera.prevPosX, camera.posX, partialTicks);
this.cY = Interpolations.lerp(camera.prevPosY, camera.posY, partialTicks) + camera.getEyeHeight();
this.cZ = Interpolations.lerp(camera.prevPosZ, camera.posZ, partialTicks);
}
}
/**
* Get brightness for the block
*/
public int getBrightnessForRender(float partialTicks, double x, double y, double z)
{
if (this.lit || this.world == null)
{
return 15728880;
}
this.blockPos.setPos(x, y, z);
return this.world.isBlockLoaded(this.blockPos) ? this.world.getCombinedLight(this.blockPos, 0) : 0;
}
} | 25,183 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockParticle.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/emitter/BedrockParticle.java | package mchorse.blockbuster.client.particles.emitter;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionAppearance;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionTinting;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.DummyEntity;
import mchorse.mclib.utils.MathUtils;
import mchorse.mclib.utils.MatrixUtils;
import mchorse.metamorph.api.Morph;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.vecmath.*;
import java.util.HashMap;
import java.util.Map;
public class BedrockParticle
{
/* Randoms */
public float random1 = (float) Math.random();
public float random2 = (float) Math.random();
public float random3 = (float) Math.random();
public float random4 = (float) Math.random();
public Morph morph = new Morph();
private DummyEntity dummy;
/* States */
public int age;
public int lifetime;
public boolean dead;
public boolean relativePosition;
public boolean relativeRotation;
public boolean relativeDirection;
public boolean relativeScale;
public boolean relativeScaleBillboard;
public boolean relativeAcceleration;
public boolean realisticCollisionDrag;
public float linearVelocity;
public float angularVelocity;
public boolean gravity;
public boolean manual;
/* Age when the particle should expire */
private int expireAge = -1;
/* Used to determine lifetime when expirationDelay is on */
private int expirationDelay = -1;
/**
* This is used to estimate whether an object is only bouncing or lying on a surface
*
* CollisionTime won't work when e.g. the particle bounces of the surface and directly in the next
* update cycle hits the same surface side, like from top of the block to bottom of the block...
* I think this probably never happens in practice
*/
public Vector3f collisionTime = new Vector3f(-2f, -2f,-2f);
public HashMap<Entity, Vector3f> entityCollisionTime = new HashMap<>();
public boolean collided;
public int bounces;
/**
* Is set by collision component when there is a collision an drag should happen.
*/
public float rotationCollisionDrag = 0;
/**
* For collision Appearance needed for animation
*/
public int firstIntersection = -1;
public boolean intersected;
/* Rotation */
public float rotation;
public float initialRotation;
public float prevRotation;
public float rotationVelocity;
public float rotationAcceleration;
public float rotationDrag;
/* for transforming into intertial systems (currently just used for inertia)*/
public Vector3d offset = new Vector3d();
/* Position */
public Vector3d position = new Vector3d();
public Vector3d initialPosition = new Vector3d();
public Vector3d prevPosition = new Vector3d();
public Matrix3f matrix = new Matrix3f();
private boolean matrixSet;
public Vector3f speed = new Vector3f();
public Vector3f acceleration = new Vector3f();
public Vector3f accelerationFactor = new Vector3f(1, 1, 1);
public float drag = 0;
/**
* Is set by collision component when there is a collision an drag should happen.
*/
public float dragFactor = 0;
/* Color */
public float r = 1;
public float g = 1;
public float b = 1;
public float a = 1;
private Vector3d global = new Vector3d();
public BedrockParticle()
{
this.speed.set((float) Math.random() - 0.5F, (float) Math.random() - 0.5F, (float) Math.random() - 0.5F);
this.speed.normalize();
this.matrix.setIdentity();
}
public boolean isCollisionTexture(BedrockEmitter emitter)
{
return MolangExpression.isOne(emitter.scheme.getOrCreate(BedrockComponentCollisionAppearance.class).enabled) && this.intersected;
}
public boolean isCollisionTinting(BedrockEmitter emitter)
{
return MolangExpression.isOne(emitter.scheme.getOrCreate(BedrockComponentCollisionTinting.class).enabled) && this.intersected;
}
public int getExpireAge()
{
return this.expireAge;
}
public int getExpirationDelay()
{
return this.expirationDelay;
}
/**
* Copy this particle to the given particle (it does not copy fields that are initialized by components)
* @param to destiny to copy values to
* @return copied particle
*/
public BedrockParticle softCopy(BedrockParticle to)
{
to.age = this.age;
to.expireAge = this.expireAge;
to.expirationDelay = this.expirationDelay;
to.realisticCollisionDrag = this.realisticCollisionDrag;
to.collisionTime = (Vector3f) this.collisionTime.clone();
to.entityCollisionTime = new HashMap<>();
for(Map.Entry<Entity, Vector3f> entry : this.entityCollisionTime.entrySet())
{
to.entityCollisionTime.put(entry.getKey(), (Vector3f) entry.getValue().clone());
}
to.bounces = this.bounces;
to.firstIntersection = this.firstIntersection;
to.offset = (Vector3d) this.offset.clone();
to.position = (Vector3d) this.position.clone();
to.initialPosition = (Vector3d) this.initialPosition.clone();
to.prevPosition = (Vector3d) this.prevPosition.clone();
to.matrix = (Matrix3f) this.matrix.clone();
to.matrixSet = this.matrixSet;
to.speed = (Vector3f) this.speed.clone();
to.acceleration = (Vector3f) this.acceleration.clone();
to.accelerationFactor = (Vector3f) this.accelerationFactor.clone();
to.dragFactor = this.dragFactor;
to.global = (Vector3d) this.global.clone();
return to;
}
public double getDistanceSq(BedrockEmitter emitter)
{
Vector3d pos = this.getGlobalPosition(emitter);
double dx = emitter.cX - pos.x;
double dy = emitter.cY - pos.y;
double dz = emitter.cZ - pos.z;
return dx * dx + dy * dy + dz * dz;
}
public double getAge(float partialTick)
{
return (this.age + partialTick) / 20.0;
}
public Vector3d getGlobalPosition(BedrockEmitter emitter)
{
return this.getGlobalPosition(emitter, this.position);
}
public Vector3d getGlobalPosition(BedrockEmitter emitter, Vector3d vector)
{
double px = vector.x;
double py = vector.y;
double pz = vector.z;
if (this.relativePosition && this.relativeRotation)
{
Vector3f v = new Vector3f((float) px, (float) py, (float) pz);
emitter.rotation.transform(v);
px = v.x;
py = v.y;
pz = v.z;
px += emitter.lastGlobal.x;
py += emitter.lastGlobal.y;
pz += emitter.lastGlobal.z;
}
this.global.set(px, py, pz);
return this.global;
}
public void update(BedrockEmitter emitter)
{
this.prevRotation = this.rotation;
this.prevPosition.set(this.position);
this.setupMatrix(emitter);
if (!this.manual)
{
//this.position.add(this.offset);
/*if (this.realisticCollisionDrag && Math.round(this.speed.x*10000) == 0 && Math.round(this.speed.y*10000) == 0 && Math.round(this.speed.z*10000) == 0)
{
this.dragFactor = 0;
this.speed.scale(0);
}*/
/* lazy fix for transforming from moving intertial system back to global space */
if (this.entityCollisionTime.isEmpty())
{
transformOffsetToGlobal();
}
else
{
for (HashMap.Entry<Entity, Vector3f> entry : this.entityCollisionTime.entrySet())
{
if (entry.getValue().y != this.age)
{
transformOffsetToGlobal();
}
}
}
//TODO drag force usually takes velocity^2 -> this cuts off higher velocities much quicker but takes longer with slower velocities. maybe two separate options?
float rotationDrag = (this.rotationDrag + this.rotationCollisionDrag) * this.rotationVelocity;
float rotationAcceleration = this.rotationAcceleration / 20F;
/* clamp drag so it doesn't make rotation velocity explode*/
this.rotationVelocity = MathUtils.clamp(this.rotationVelocity - rotationDrag / 20F,
Math.min(this.rotationVelocity, 0), Math.max(this.rotationVelocity, 0));
this.rotationVelocity += rotationAcceleration / 20F;
this.rotation += this.rotationVelocity;
/* Position */
if (this.age == 0)
{
if (this.relativeDirection)
{
emitter.rotation.transform(this.speed);
}
if (this.linearVelocity != 0)
{
Vector3f v = new Vector3f(emitter.lastGlobal);
v.x -= emitter.prevGlobal.x;
v.y -= emitter.prevGlobal.y;
v.z -= emitter.prevGlobal.z;
this.speed.x += v.x * this.linearVelocity;
this.speed.y += v.y * this.linearVelocity;
this.speed.z += v.z * this.linearVelocity;
}
if (this.angularVelocity != 0)
{
Matrix3f rotation1 = new Matrix3f(emitter.rotation);
Matrix3f identity = new Matrix3f();
identity.setIdentity();
try
{
Matrix3f rotation0 = new Matrix3f(emitter.prevRotation);
rotation0.invert();
rotation1.mul(rotation0);
Vector3f angularV = MatrixUtils.getAngularVelocity(rotation1);
Vector3f radius = new Vector3f(emitter.translation);
radius.x += this.position.x - emitter.lastGlobal.x;
radius.y += this.position.y - emitter.lastGlobal.y;
radius.z += this.position.z - emitter.lastGlobal.z;
Vector3f v = new Vector3f();
v.cross(angularV, radius);
this.speed.x += v.x * this.angularVelocity;
this.speed.y += v.y * this.angularVelocity;
this.speed.z += v.z * this.angularVelocity;
}
catch (SingularMatrixException e) {} //maybe check if determinant is zero
}
}
if (this.relativeAcceleration)
{
emitter.rotation.transform(this.acceleration);
}
if (this.gravity)
{
this.acceleration.y -= 9.81;
}
Vector3f drag = new Vector3f(this.speed);
drag.scale(-(this.drag + this.dragFactor));
/* apply drag separately so we can clamp it - high drag values shouldn't accelerate particles again */
drag.scale(1 / 20F);
if (this.speed.length() - drag.length() <= 0) {
this.speed.scale(0);
} else {
this.speed.add(drag);
}
this.acceleration.scale(1 / 20F);
this.speed.add(this.acceleration);
Vector3f speed0 = new Vector3f(this.speed);
speed0.x *= this.accelerationFactor.x;
speed0.y *= this.accelerationFactor.y;
speed0.z *= this.accelerationFactor.z;
if (this.relativePosition || this.relativeRotation)
{
this.matrix.transform(speed0);
}
this.position.x += speed0.x / 20F;
this.position.y += speed0.y / 20F;
this.position.z += speed0.z / 20F;
if (!this.morph.isEmpty())
{
EntityLivingBase dummy = this.getDummy(emitter);
this.morph.get().update(dummy);
dummy.ticksExisted += 1;
}
}
if (this.lifetime >= 0 &&
(this.age >= this.lifetime || (this.age >= this.expireAge && this.expireAge != -1)) )
{
this.dead = true;
}
this.age ++;
this.acceleration.set(0,0,0);
}
/**
* Sets the expirationDelay and expireAge - the smallest expire age wins. Negative expiration delays always overwrite/win.
*/
public void setExpirationDelay(double delay)
{
int expirationDelay = (int) delay;
if (this.age + expirationDelay < this.expireAge || this.expireAge == -1)
{
this.expirationDelay = Math.abs(expirationDelay);
this.expireAge = this.age + this.expirationDelay;
}
}
public void setupMatrix(BedrockEmitter emitter)
{
if (this.relativePosition)
{
if (this.relativeRotation)
{
this.matrix.setIdentity();
}
else if (!this.matrixSet)
{
this.matrix.set(emitter.rotation);
this.matrixSet = true;
}
}
else if (this.relativeRotation)
{
this.matrix.set(emitter.rotation);
}
}
/**
* This method adds the offset to the speed to transform from a moving inertial system to the global space
* (especially for inertia)
*/
public void transformOffsetToGlobal()
{
this.offset.scale(6); //scale it up so it gets more noticeable (artistic choice)
this.speed.x += this.offset.x;
this.speed.y += this.offset.y;
this.speed.z += this.offset.z;
this.offset.scale(0);
}
@SideOnly(Side.CLIENT)
public EntityLivingBase getDummy(BedrockEmitter emitter)
{
if (this.dummy == null)
{
this.dummy = new DummyEntity(Minecraft.getMinecraft().world);
}
Vector3d pos = this.getGlobalPosition(emitter);
this.dummy.setPosition(pos.x, pos.y, pos.z);
this.dummy.prevPosX = this.dummy.posX;
this.dummy.prevPosY = this.dummy.posY;
this.dummy.prevPosZ = this.dummy.posZ;
this.dummy.lastTickPosX = this.dummy.posX;
this.dummy.lastTickPosY = this.dummy.posY;
this.dummy.lastTickPosZ = this.dummy.posZ;
this.dummy.rotationYaw = this.dummy.prevRotationYaw = 0;
this.dummy.rotationPitch = this.dummy.prevRotationPitch = 0;
this.dummy.rotationYawHead = this.dummy.prevRotationYawHead = 0;
this.dummy.renderYawOffset = this.dummy.prevRenderYawOffset = 0;
return this.dummy;
}
}
| 15,081 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentBase.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/BedrockComponentBase.java | package mchorse.blockbuster.client.particles.components;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
public abstract class BedrockComponentBase
{
public BedrockComponentBase fromJson(JsonElement element, MolangParser parser) throws MolangException
{
return this;
}
public JsonElement toJson()
{
return new JsonObject();
}
public boolean canBeEmpty()
{
return false;
}
} | 557 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentParticleMorphRender.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentParticleMorphRender.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import net.minecraft.client.renderer.BufferBuilder;
public interface IComponentParticleMorphRender extends IComponentRenderBase
{ }
| 328 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentRenderBase.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentRenderBase.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import net.minecraft.client.renderer.BufferBuilder;
public interface IComponentRenderBase extends IComponentBase
{
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks);
public void renderOnScreen(BedrockParticle particle, int x, int y, float scale, float partialTicks);
public void preRender(BedrockEmitter emitter, float partialTicks);
public void postRender(BedrockEmitter emitter, float partialTicks);
}
| 681 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentEmitterInitialize.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentEmitterInitialize.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
public interface IComponentEmitterInitialize extends IComponentBase
{
public void apply(BedrockEmitter emitter);
} | 245 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentBase.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentBase.java | package mchorse.blockbuster.client.particles.components;
public interface IComponentBase
{
public default int getSortingIndex()
{
return 0;
}
} | 164 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentParticleUpdate.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentParticleUpdate.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
public interface IComponentParticleUpdate extends IComponentBase
{
public void update(BedrockEmitter emitter, BedrockParticle particle);
} | 338 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentParticleRender.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentParticleRender.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import net.minecraft.client.renderer.BufferBuilder;
public interface IComponentParticleRender extends IComponentRenderBase
{
} | 322 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentEmitterUpdate.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentEmitterUpdate.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
public interface IComponentEmitterUpdate extends IComponentBase
{
public void update(BedrockEmitter emitter);
} | 242 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IComponentParticleInitialize.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/IComponentParticleInitialize.java | package mchorse.blockbuster.client.particles.components;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
public interface IComponentParticleInitialize extends IComponentBase
{
public void apply(BedrockEmitter emitter, BedrockParticle particle);
} | 341 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentExpireBlocks.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/expiration/BedrockComponentExpireBlocks.java | package mchorse.blockbuster.client.particles.components.expiration;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import javax.vecmath.Vector3d;
import java.util.ArrayList;
import java.util.List;
public abstract class BedrockComponentExpireBlocks extends BedrockComponentBase
{
public List<Block> blocks = new ArrayList<Block>();
private BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
@Override
public BedrockComponentBase fromJson(JsonElement element, MolangParser parser) throws MolangException
{
if (element.isJsonArray())
{
for (JsonElement value : element.getAsJsonArray())
{
ResourceLocation location = new ResourceLocation(value.getAsString());
Block block = ForgeRegistries.BLOCKS.getValue(location);
if (block != null)
{
this.blocks.add(block);
}
}
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonArray array = new JsonArray();
for (Block block : this.blocks)
{
ResourceLocation rl = ForgeRegistries.BLOCKS.getKey(block);
if (rl != null)
{
array.add(rl.toString());
}
}
return array;
}
public Block getBlock(BedrockEmitter emitter, BedrockParticle particle)
{
if (emitter.world == null)
{
return Blocks.AIR;
}
Vector3d position = particle.getGlobalPosition(emitter);
this.pos.setPos(position.getX(), position.getY(), position.getZ());
return emitter.world.getBlockState(this.pos).getBlock();
}
} | 2,310 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentExpireNotInBlocks.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/expiration/BedrockComponentExpireNotInBlocks.java | package mchorse.blockbuster.client.particles.components.expiration;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import net.minecraft.block.Block;
public class BedrockComponentExpireNotInBlocks extends BedrockComponentExpireBlocks implements IComponentParticleUpdate
{
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
if (particle.dead || emitter.world == null)
{
return;
}
Block current = this.getBlock(emitter, particle);
for (Block block : this.blocks)
{
if (block == current)
{
return;
}
}
particle.dead = true;
}
} | 873 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentKillPlane.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/expiration/BedrockComponentKillPlane.java | package mchorse.blockbuster.client.particles.components.expiration;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.Operation;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import javax.vecmath.Vector3d;
public class BedrockComponentKillPlane extends BedrockComponentBase implements IComponentParticleUpdate
{
public float a;
public float b;
public float c;
public float d;
@Override
public BedrockComponentBase fromJson(JsonElement element, MolangParser parser) throws MolangException
{
if (!element.isJsonArray())
{
return super.fromJson(element, parser);
}
JsonArray array = element.getAsJsonArray();
if (array.size() >= 4)
{
this.a = array.get(0).getAsFloat();
this.b = array.get(1).getAsFloat();
this.c = array.get(2).getAsFloat();
this.d = array.get(3).getAsFloat();
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonArray array = new JsonArray();
if (Operation.equals(this.a, 0) && Operation.equals(this.b, 0) && Operation.equals(this.c, 0) && Operation.equals(this.d, 0))
{
return array;
}
array.add(this.a);
array.add(this.b);
array.add(this.c);
array.add(this.d);
return array;
}
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
if (particle.dead)
{
return;
}
Vector3d prevLocal = new Vector3d(particle.prevPosition);
Vector3d local = new Vector3d(particle.position);
if (!particle.relativePosition)
{
local.sub(emitter.lastGlobal);
prevLocal.sub(emitter.lastGlobal);
}
double prev = this.a * prevLocal.x + this.b * prevLocal.y + this.c * prevLocal.z + this.d;
double now = this.a * local.x + this.b * local.y + this.c * local.z + this.d;
if ((prev > 0 && now < 0) || (prev < 0 && now > 0))
{
particle.dead = true;
}
}
@Override
public int getSortingIndex()
{
return 100;
}
} | 2,614 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentParticleLifetime.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/expiration/BedrockComponentParticleLifetime.java | package mchorse.blockbuster.client.particles.components.expiration;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentParticleLifetime extends BedrockComponentBase implements IComponentParticleInitialize, IComponentParticleUpdate
{
public MolangExpression expression = MolangParser.ZERO;
public boolean max;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
JsonElement expression = null;
if (element.has("expiration_expression"))
{
expression = element.get("expiration_expression");
this.max = false;
}
else if (element.has("max_lifetime"))
{
expression = element.get("max_lifetime");
this.max = true;
}
else
{
throw new JsonParseException("No expiration_expression or max_lifetime was found in minecraft:particle_lifetime_expression component");
}
this.expression = parser.parseJson(expression);
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
object.add(this.max ? "max_lifetime" : "expiration_expression", this.expression.toJson());
return object;
}
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
if (!this.max && this.expression.get() != 0)
{
particle.dead = true;
}
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
if (this.max)
{
particle.lifetime = (int) (this.expression.get() * 20);
}
else
{
particle.lifetime = -1;
}
}
} | 2,560 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentExpireInBlocks.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/expiration/BedrockComponentExpireInBlocks.java | package mchorse.blockbuster.client.particles.components.expiration;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import net.minecraft.block.Block;
public class BedrockComponentExpireInBlocks extends BedrockComponentExpireBlocks implements IComponentParticleUpdate
{
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
if (particle.dead || emitter.world == null)
{
return;
}
Block current = this.getBlock(emitter, particle);
for (Block block : this.blocks)
{
if (block == current)
{
particle.dead = true;
return;
}
}
}
} | 878 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentLifetimeExpression.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/lifetime/BedrockComponentLifetimeExpression.java | package mchorse.blockbuster.client.particles.components.lifetime;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.mclib.math.Operation;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentLifetimeExpression extends BedrockComponentLifetime
{
public MolangExpression expiration = MolangParser.ZERO;
@Override
protected String getPropertyName()
{
return "activation_expression";
}
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject())
{
return super.fromJson(elem, parser);
}
JsonObject element = elem.getAsJsonObject();
if (element.has("expiration_expression"))
{
this.expiration = parser.parseJson(element.get("expiration_expression"));
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = (JsonObject) super.toJson();
if (!MolangExpression.isZero(this.expiration))
{
object.add("expiration_expression", this.expiration.toJson());
}
return object;
}
@Override
public void update(BedrockEmitter emitter)
{
if (!Operation.equals(this.activeTime.get(), 0))
{
emitter.start();
}
if (!Operation.equals(this.expiration.get(), 0))
{
emitter.stop();
}
}
} | 1,787 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentLifetime.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/lifetime/BedrockComponentLifetime.java | package mchorse.blockbuster.client.particles.components.lifetime;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentEmitterUpdate;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangValue;
public abstract class BedrockComponentLifetime extends BedrockComponentBase implements IComponentEmitterUpdate
{
public static final MolangExpression DEFAULT_ACTIVE = new MolangValue(null, new Constant(10));
public MolangExpression activeTime = DEFAULT_ACTIVE;
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject())
{
return super.fromJson(elem, parser);
}
JsonObject element = elem.getAsJsonObject();
if (element.has(this.getPropertyName()))
{
this.activeTime = parser.parseJson(element.get(this.getPropertyName()));
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (!MolangExpression.isConstant(this.activeTime, 10))
{
object.add(this.getPropertyName(), this.activeTime.toJson());
}
return object;
}
protected String getPropertyName()
{
return "active_time";
}
@Override
public int getSortingIndex()
{
return -10;
}
} | 1,747 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentLifetimeOnce.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/lifetime/BedrockComponentLifetimeOnce.java | package mchorse.blockbuster.client.particles.components.lifetime;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
public class BedrockComponentLifetimeOnce extends BedrockComponentLifetime
{
@Override
public void update(BedrockEmitter emitter)
{
double time = this.activeTime.get();
emitter.lifetime = (int) (time * 20);
if (emitter.getAge() >= time)
{
emitter.stop();
}
}
} | 466 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentLifetimeLooping.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/lifetime/BedrockComponentLifetimeLooping.java | package mchorse.blockbuster.client.particles.components.lifetime;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentLifetimeLooping extends BedrockComponentLifetime
{
public MolangExpression sleepTime = MolangParser.ZERO;
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject())
{
return super.fromJson(elem, parser);
}
JsonObject element = elem.getAsJsonObject();
if (element.has("sleep_time"))
{
this.sleepTime = parser.parseJson(element.get("sleep_time"));
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = (JsonObject) super.toJson();
if (!MolangExpression.isZero(this.sleepTime))
{
object.add("sleep_time", this.sleepTime.toJson());
}
return object;
}
@Override
public void update(BedrockEmitter emitter)
{
double active = this.activeTime.get();
double sleep = this.sleepTime.get();
double age = emitter.getAge();
emitter.lifetime = (int) (active * 20);
if (age >= active && emitter.playing)
{
emitter.stop();
}
if (age >= sleep && !emitter.playing)
{
emitter.start();
}
}
} | 1,763 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentRateSteady.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/rate/BedrockComponentRateSteady.java | package mchorse.blockbuster.client.particles.components.rate;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleMorphRender;
import mchorse.blockbuster.client.particles.components.IComponentParticleRender;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangValue;
import net.minecraft.client.renderer.BufferBuilder;
public class BedrockComponentRateSteady extends BedrockComponentRate implements IComponentParticleRender, IComponentParticleMorphRender
{
public static final MolangExpression DEFAULT_PARTICLES = new MolangValue(null, new Constant(50));
public MolangExpression spawnRate = MolangParser.ONE;
public BedrockComponentRateSteady()
{
this.particles = DEFAULT_PARTICLES;
}
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("spawn_rate")) this.spawnRate = parser.parseJson(element.get("spawn_rate"));
if (element.has("max_particles")) this.particles = parser.parseJson(element.get("max_particles"));
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (!MolangExpression.isOne(this.spawnRate)) object.add("spawn_rate", this.spawnRate.toJson());
if (!MolangExpression.isConstant(this.particles, 50)) object.add("max_particles", this.particles.toJson());
return object;
}
@Override
public void preRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks)
{}
@Override
public void renderOnScreen(BedrockParticle particle, int x, int y, float scale, float partialTicks)
{}
@Override
public void postRender(BedrockEmitter emitter, float partialTicks)
{
if (emitter.playing)
{
double particles = emitter.getAge(partialTicks) * this.spawnRate.get();
double diff = particles - emitter.spawnedParticles;
double spawn = Math.round(diff);
if (spawn > 0)
{
emitter.setEmitterVariables(partialTicks);
double track = spawn;
for (int i = 0; i < spawn; i++)
{
if (emitter.particles.size() < this.particles.get())
{
emitter.spawnParticle();
}
else
{
track -= 1;
}
}
emitter.spawnedParticles += track;
}
}
}
@Override
public int getSortingIndex()
{
return 10;
}
} | 3,405 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentRate.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/rate/BedrockComponentRate.java | package mchorse.blockbuster.client.particles.components.rate;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public abstract class BedrockComponentRate extends BedrockComponentBase
{
public MolangExpression particles;
} | 318 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentRateInstant.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/rate/BedrockComponentRateInstant.java | package mchorse.blockbuster.client.particles.components.rate;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentEmitterUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.Operation;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangValue;
public class BedrockComponentRateInstant extends BedrockComponentRate implements IComponentEmitterUpdate
{
public static final MolangExpression DEFAULT_PARTICLES = new MolangValue(null, new Constant(10));
public BedrockComponentRateInstant()
{
this.particles = DEFAULT_PARTICLES;
}
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("num_particles"))
{
this.particles = parser.parseJson(element.get("num_particles"));
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (!MolangExpression.isConstant(this.particles, 10))
{
object.add("num_particles", this.particles.toJson());
}
return object;
}
@Override
public void update(BedrockEmitter emitter)
{
double age = emitter.getAge();
if (emitter.playing && Operation.equals(age, 0))
{
emitter.setEmitterVariables(0);
for (int i = 0, c = (int) this.particles.get(); i < c; i ++)
{
emitter.spawnParticle();
}
}
}
} | 2,045 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentAppearanceLighting.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/BedrockComponentAppearanceLighting.java | package mchorse.blockbuster.client.particles.components.appearance;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentEmitterInitialize;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
public class BedrockComponentAppearanceLighting extends BedrockComponentBase implements IComponentEmitterInitialize
{
@Override
public void apply(BedrockEmitter emitter)
{
emitter.lit = false;
}
@Override
public boolean canBeEmpty()
{
return true;
}
} | 599 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentCollisionAppearance.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/BedrockComponentCollisionAppearance.java | package mchorse.blockbuster.client.particles.components.appearance;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.BedrockMaterial;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleRender;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.Interpolations;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import java.util.Map;
import java.util.Set;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
public class BedrockComponentCollisionAppearance extends BedrockComponentAppearanceBillboard implements IComponentParticleRender
{
/* Options */
public BedrockMaterial material = BedrockMaterial.OPAQUE;
public ResourceLocation texture = BedrockScheme.DEFAULT_TEXTURE;
public MolangExpression enabled = MolangParser.ZERO;
public boolean lit; //gets set from GuiCollisionLighting
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("enabled")) this.enabled = parser.parseJson(element.get("enabled"));
if (element.has("lit"))
{
this.lit = element.get("lit").getAsBoolean();
}
if (element.has("material"))
{
this.material = BedrockMaterial.fromString(element.get("material").getAsString());
}
if (element.has("texture"))
{
String texture = element.get("texture").getAsString();
if (!texture.equals("textures/particle/particles"))
{
this.texture = RLUtils.create(texture);
}
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
object.add("enabled", this.enabled.toJson());
object.addProperty("lit", this.lit);
object.addProperty("material", this.material.id);
if (this.texture != null && !this.texture.equals(BedrockScheme.DEFAULT_TEXTURE))
{
object.addProperty("texture", this.texture.toString());
}
/* add the default stuff from super */
JsonObject superJson = (JsonObject) super.toJson();
Set<Map.Entry<String, JsonElement>> entries = superJson.entrySet();
for(Map.Entry<String, JsonElement> entry : entries)
{
object.add(entry.getKey(), entry.getValue());
}
return object;
}
@Override
public void preRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks)
{
boolean tmpLit = false;
if (!particle.isCollisionTexture(emitter))
{
if (particle.isCollisionTinting(emitter))
{
tmpLit = emitter.lit;
emitter.lit = this.lit;
emitter.scheme.get(BedrockComponentAppearanceBillboard.class).render(emitter, particle, builder, partialTicks);
emitter.lit = tmpLit;
}
return; //when texture and tinting is false - this render method should not be used
}
else if (!particle.isCollisionTinting(emitter))
{
//tinting false doesn't necessarily mean that lit was not passed - emitter.lit should be used
tmpLit = this.lit;
this.lit = emitter.lit;
}
this.calculateUVs(particle, partialTicks);
/* Render the particle */
double px = Interpolations.lerp(particle.prevPosition.x, particle.position.x, partialTicks);
double py = Interpolations.lerp(particle.prevPosition.y, particle.position.y, partialTicks);
double pz = Interpolations.lerp(particle.prevPosition.z, particle.position.z, partialTicks);
float angle = Interpolations.lerp(particle.prevRotation, particle.rotation, partialTicks);
Vector3d pos = this.calculatePosition(emitter, particle, px, py, pz);
px = pos.x;
py = pos.y;
pz = pos.z;
/* Calculate the geometry for billboards using cool matrix math */
int light = this.lit ? 15728880 : emitter.getBrightnessForRender(partialTicks, px, py, pz);
int lightX = light >> 16 & 65535;
int lightY = light & 65535;
this.calculateFacing(emitter, particle, px, py, pz);
this.rotation.rotZ(angle / 180 * (float) Math.PI);
this.transform.mul(this.rotation);
this.transform.setTranslation(new Vector3f((float) px, (float) py, (float) pz));
for (Vector4f vertex : this.vertices)
{
this.transform.transform(vertex);
}
float u1 = this.u1 / (float) this.textureWidth;
float u2 = this.u2 / (float) this.textureWidth;
float v1 = this.v1 / (float) this.textureHeight;
float v2 = this.v2 / (float) this.textureHeight;
builder.pos(this.vertices[0].x, this.vertices[0].y, this.vertices[0].z).tex(u1, v1).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[1].x, this.vertices[1].y, this.vertices[1].z).tex(u2, v1).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[2].x, this.vertices[2].y, this.vertices[2].z).tex(u2, v2).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[3].x, this.vertices[3].y, this.vertices[3].z).tex(u1, v2).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
if (!particle.isCollisionTinting(emitter))
{
this.lit = tmpLit;
}
}
@Override //not really important because it seems to be used for guiParticles - there is no collision
public void renderOnScreen(BedrockParticle particle, int x, int y, float scale, float partialTicks)
{ }
@Override
public void calculateUVs(BedrockParticle particle, float partialTicks)
{
/* Update particle's UVs and size */
this.w = (float) this.sizeW.get() * 2.25F;
this.h = (float) this.sizeH.get() * 2.25F;
float u = (float) this.uvX.get();
float v = (float) this.uvY.get();
float w = (float) this.uvW.get();
float h = (float) this.uvH.get();
if (this.flipbook)
{
int index = (int) (particle.getAge(partialTicks) * this.fps);
int max = (int) this.maxFrame.get();
if (this.stretchFPS)
{
float lifetime = (particle.lifetime <= 0) ? 0 : (particle.age + partialTicks) / (particle.lifetime - particle.firstIntersection);
//for collided particles with expiration - stretch differently since lifetime changed
if (particle.getExpireAge() != -1)
{
lifetime = (particle.lifetime <= 0) ? 0 : (particle.age + partialTicks) / (particle.getExpirationDelay());
}
index = (int) (lifetime * max);
}
if (this.loop && max != 0)
{
index = index % max;
}
if (index > max)
{
index = max;
}
u += this.stepX * index;
v += this.stepY * index;
}
this.u1 = u;
this.v1 = v;
this.u2 = u + w;
this.v2 = v + h;
}
@Override
public void postRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public int getSortingIndex()
{
return 200;
}
} | 8,565 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentCollisionTinting.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/BedrockComponentCollisionTinting.java | package mchorse.blockbuster.client.particles.components.appearance;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.BedrockSchemeJsonAdapter;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleRender;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import net.minecraft.client.renderer.BufferBuilder;
import java.util.Map;
import java.util.Set;
public class BedrockComponentCollisionTinting extends BedrockComponentAppearanceTinting implements IComponentParticleRender
{
public MolangExpression enabled = MolangParser.ZERO;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("enabled")) this.enabled = parser.parseJson(element.get("enabled"));
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
object.add("enabled", this.enabled.toJson());
/* add the default stuff from super */
JsonObject superJson = (JsonObject) super.toJson();
Set<Map.Entry<String, JsonElement>> entries = superJson.entrySet();
for(Map.Entry<String, JsonElement> entry : entries)
{
object.add(entry.getKey(), entry.getValue());
}
return object;
}
@Override
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks)
{
if (particle.isCollisionTinting(emitter))
{
this.renderOnScreen(particle, 0, 0, 0, 0);
}
}
@Override
public int getSortingIndex()
{
return -5;
}
} | 2,273 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentParticleMorph.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/BedrockComponentParticleMorph.java | package mchorse.blockbuster.client.particles.components.appearance;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.components.IComponentParticleMorphRender;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.utils.Interpolations;
import mchorse.metamorph.api.Morph;
import mchorse.metamorph.api.MorphManager;
import mchorse.metamorph.api.MorphUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTException;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.vecmath.Matrix3d;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
public class BedrockComponentParticleMorph extends BedrockComponentBase implements IComponentParticleMorphRender, IComponentParticleInitialize
{
public boolean enabled;
public boolean renderTexture;
public Morph morph = new Morph();
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("enabled")) this.enabled = element.get("enabled").getAsBoolean();
if (element.has("render_texture")) this.renderTexture = element.get("render_texture").getAsBoolean();
if (element.has("nbt"))
{
try
{
this.morph.setDirect(MorphManager.INSTANCE.morphFromNBT(JsonToNBT.getTagFromJson(element.get("nbt").getAsString())));
}
catch(NBTException e) { }
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
object.addProperty("enabled", this.enabled);
object.addProperty("render_texture", this.renderTexture);
if (!this.morph.isEmpty()) object.addProperty("nbt", this.morph.toNBT().toString());
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
if (this.enabled && !this.morph.isEmpty())
{
particle.morph.set(MorphUtils.copy(this.morph.get()));
}
}
@SideOnly(Side.CLIENT)
@Override
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks)
{
Entity camera = Minecraft.getMinecraft().getRenderViewEntity();
if (camera == null || this.morph.isEmpty() || !this.enabled)
{
return;
}
EntityLivingBase dummy = particle.getDummy(emitter);
double x = Interpolations.lerp(particle.prevPosition.x, particle.position.x, partialTicks);
double y = Interpolations.lerp(particle.prevPosition.y, particle.position.y, partialTicks);
double z = Interpolations.lerp(particle.prevPosition.z, particle.position.z, partialTicks);
Vector3d position = this.calculatePosition(emitter, particle, x, y, z);
x = position.x;
y = position.y;
z = position.z;
if (!GuiModelRenderer.isRendering())
{
x -= Interpolations.lerp(camera.prevPosX, camera.posX, partialTicks);
y -= Interpolations.lerp(camera.prevPosY, camera.posY, partialTicks);
z -= Interpolations.lerp(camera.prevPosZ, camera.posZ, partialTicks);
}
int combinedBrightness = dummy.getBrightnessForRender();
int brightnessX = combinedBrightness % 65536;
int brightnessY = combinedBrightness / 65536;
GlStateManager.color(1, 1, 1, 1);
RenderHelper.enableStandardItemLighting();
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, brightnessX, brightnessY);
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
if (particle.relativeScaleBillboard)
{
GlStateManager.scale(emitter.scale[0], emitter.scale[1], emitter.scale[2]);
}
MorphUtils.render(this.morph.get(), dummy, 0, 0, 0, 0, partialTicks);
RenderHelper.disableStandardItemLighting();
GlStateManager.popMatrix();
}
protected Vector3d calculatePosition(BedrockEmitter emitter, BedrockParticle particle, double px, double py, double pz)
{
if (particle.relativePosition && particle.relativeRotation)
{
Vector3f vector = new Vector3f((float) px, (float) py, (float) pz);
emitter.rotation.transform(vector);
px = vector.x;
py = vector.y;
pz = vector.z;
if (particle.relativeScale)
{
Vector3d pos = new Vector3d(px, py, pz);
Matrix3d scale = new Matrix3d(emitter.scale[0], 0, 0,
0, emitter.scale[1], 0,
0, 0, emitter.scale[2]);
scale.transform(pos);
px = pos.x;
py = pos.y;
pz = pos.z;
}
px += emitter.lastGlobal.x;
py += emitter.lastGlobal.y;
pz += emitter.lastGlobal.z;
}
else if (particle.relativeScale)
{
Vector3d pos = new Vector3d(px, py, pz);
Matrix3d scale = new Matrix3d(emitter.scale[0], 0, 0,
0, emitter.scale[1], 0,
0, 0, emitter.scale[2]);
pos.sub(emitter.lastGlobal); //transform back to local
scale.transform(pos);
pos.add(emitter.lastGlobal); //transform back to global
px = pos.x;
py = pos.y;
pz = pos.z;
}
return new Vector3d(px, py, pz);
}
@SideOnly(Side.CLIENT)
@Override
public void renderOnScreen(BedrockParticle particle, int x, int y, float scale, float partialTicks)
{
if (this.enabled && !particle.morph.isEmpty() && particle.morph.get() != null)
{
particle.morph.get().renderOnScreen(Minecraft.getMinecraft().player, x, y, scale, 1F);
}
}
@Override
public void preRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public void postRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public int getSortingIndex()
{
return 99;
}
}
| 7,162 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentAppearanceTinting.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/BedrockComponentAppearanceTinting.java | package mchorse.blockbuster.client.particles.components.appearance;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.BedrockSchemeJsonAdapter;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleRender;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import net.minecraft.client.renderer.BufferBuilder;
public class BedrockComponentAppearanceTinting extends BedrockComponentBase implements IComponentParticleRender
{
public Tint color = new Tint.Solid();
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("color"))
{
JsonElement color = element.get("color");
if (color.isJsonArray() || color.isJsonPrimitive())
{
this.color = Tint.parseColor(color, parser);
}
else if (color.isJsonObject())
{
this.color = Tint.parseGradient(color.getAsJsonObject(), parser);
}
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
JsonElement element = this.color.toJson();
if (!BedrockSchemeJsonAdapter.isEmpty(element))
{
object.add("color", element);
}
return object;
}
/* Interface implementations */
@Override
public void preRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks)
{
this.renderOnScreen(particle, 0, 0, 0, 0);
}
@Override
public void renderOnScreen(BedrockParticle particle, int x, int y, float scale, float partialTicks)
{
if (this.color != null)
{
this.color.compute(particle);
}
else
{
particle.r = particle.g = particle.b = particle.a = 1;
}
}
@Override
public void postRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public int getSortingIndex()
{
return -10;
}
} | 2,652 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
CameraFacing.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/CameraFacing.java | package mchorse.blockbuster.client.particles.components.appearance;
/**
* Camera facing mode
*/
public enum CameraFacing
{
ROTATE_XYZ("rotate_xyz"), ROTATE_Y("rotate_y"),
LOOKAT_XYZ("lookat_xyz", true, false), LOOKAT_Y("lookat_y", true, false), LOOKAT_DIRECTION("lookat_direction", true, true),
DIRECTION_X("direction_x", false, true), DIRECTION_Y("direction_y", false, true), DIRECTION_Z("direction_z", false, true),
EMITTER_XY("emitter_transform_xy"), EMITTER_XZ("emitter_transform_xz"), EMITTER_YZ("emitter_transform_yz");
public final String id;
public final boolean isLookAt;
public final boolean isDirection;
public static CameraFacing fromString(String string)
{
for (CameraFacing facing : values())
{
if (facing.id.equals(string))
{
return facing;
}
}
return ROTATE_XYZ;
}
private CameraFacing(String id, boolean isLookAt, boolean isDirection)
{
this.id = id;
this.isLookAt = isLookAt;
this.isDirection = isDirection;
}
private CameraFacing(String id)
{
this(id, false, false);
}
}
| 1,179 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentAppearanceBillboard.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/BedrockComponentAppearanceBillboard.java | package mchorse.blockbuster.client.particles.components.appearance;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleRender;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.Interpolations;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.opengl.GL11;
import javax.vecmath.Matrix3d;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
public class BedrockComponentAppearanceBillboard extends BedrockComponentBase implements IComponentParticleRender
{
/* Options */
public MolangExpression sizeW = MolangParser.ZERO;
public MolangExpression sizeH = MolangParser.ZERO;
public CameraFacing facing = CameraFacing.LOOKAT_XYZ;
public boolean customDirection = false;
public float directionSpeedThreshhold = 0.01F;
public MolangExpression directionX = MolangParser.ZERO;
public MolangExpression directionY = MolangParser.ZERO;
public MolangExpression directionZ = MolangParser.ZERO;
public int textureWidth = 128;
public int textureHeight = 128;
public MolangExpression uvX = MolangParser.ZERO;
public MolangExpression uvY = MolangParser.ZERO;
public MolangExpression uvW = MolangParser.ZERO;
public MolangExpression uvH = MolangParser.ZERO;
public boolean flipbook = false;
public float stepX;
public float stepY;
public float fps;
public MolangExpression maxFrame = MolangParser.ZERO;
public boolean stretchFPS = false;
public boolean loop = false;
/* Runtime properties */
protected float w;
protected float h;
protected float u1;
protected float v1;
protected float u2;
protected float v2;
protected Matrix4f transform = new Matrix4f();
protected Matrix4f rotation = new Matrix4f();
protected Vector4f[] vertices = new Vector4f[] {
new Vector4f(0, 0, 0, 1),
new Vector4f(0, 0, 0, 1),
new Vector4f(0, 0, 0, 1),
new Vector4f(0, 0, 0, 1)
};
protected Vector3f vector = new Vector3f();
protected Vector3f direction = new Vector3f();
public BedrockComponentAppearanceBillboard()
{}
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("size") && element.get("size").isJsonArray())
{
JsonArray size = element.getAsJsonArray("size");
if (size.size() >= 2)
{
this.sizeW = parser.parseJson(size.get(0));
this.sizeH = parser.parseJson(size.get(1));
}
}
if (element.has("facing_camera_mode"))
{
this.facing = CameraFacing.fromString(element.get("facing_camera_mode").getAsString());
}
if (this.facing.isDirection && element.has("direction"))
{
this.parseDirection(element.get("direction").getAsJsonObject(), parser);
}
if (element.has("uv") && element.get("uv").isJsonObject())
{
this.parseUv(element.get("uv").getAsJsonObject(), parser);
}
return super.fromJson(element, parser);
}
protected void parseDirection(JsonObject object, MolangParser parser) throws MolangException
{
this.customDirection = object.has("mode") && object.get("mode").getAsString().equals("custom");
if (this.customDirection && object.has("custom_direction"))
{
JsonArray directionArray = object.getAsJsonArray("custom_direction");
this.directionX = parser.parseJson(directionArray.get(0));
this.directionY = parser.parseJson(directionArray.get(1));
this.directionZ = parser.parseJson(directionArray.get(2));
}
else if (!this.customDirection && object.has("min_speed_threshold"))
{
this.directionSpeedThreshhold = object.get("min_speed_threshold").getAsFloat();
}
}
protected void parseUv(JsonObject object, MolangParser parser) throws MolangException
{
if (object.has("texture_width")) this.textureWidth = object.get("texture_width").getAsInt();
if (object.has("texture_height")) this.textureHeight = object.get("texture_height").getAsInt();
if (object.has("uv") && object.get("uv").isJsonArray())
{
JsonArray uv = object.getAsJsonArray("uv");
if (uv.size() >= 2)
{
this.uvX = parser.parseJson(uv.get(0));
this.uvY = parser.parseJson(uv.get(1));
}
}
if (object.has("uv_size") && object.get("uv_size").isJsonArray())
{
JsonArray uv = object.getAsJsonArray("uv_size");
if (uv.size() >= 2)
{
this.uvW = parser.parseJson(uv.get(0));
this.uvH = parser.parseJson(uv.get(1));
}
}
if (object.has("flipbook") && object.get("flipbook").isJsonObject())
{
this.flipbook = true;
this.parseFlipbook(object.get("flipbook").getAsJsonObject(), parser);
}
}
protected void parseFlipbook(JsonObject flipbook, MolangParser parser) throws MolangException
{
if (flipbook.has("base_UV") && flipbook.get("base_UV").isJsonArray())
{
JsonArray uv = flipbook.getAsJsonArray("base_UV");
if (uv.size() >= 2)
{
this.uvX = parser.parseJson(uv.get(0));
this.uvY = parser.parseJson(uv.get(1));
}
}
if (flipbook.has("size_UV") && flipbook.get("size_UV").isJsonArray())
{
JsonArray uv = flipbook.getAsJsonArray("size_UV");
if (uv.size() >= 2)
{
this.uvW = parser.parseJson(uv.get(0));
this.uvH = parser.parseJson(uv.get(1));
}
}
if (flipbook.has("step_UV") && flipbook.get("step_UV").isJsonArray())
{
JsonArray uv = flipbook.getAsJsonArray("step_UV");
if (uv.size() >= 2)
{
this.stepX = uv.get(0).getAsFloat();
this.stepY = uv.get(1).getAsFloat();
}
}
if (flipbook.has("frames_per_second")) this.fps = flipbook.get("frames_per_second").getAsFloat();
if (flipbook.has("max_frame")) this.maxFrame = parser.parseJson(flipbook.get("max_frame"));
if (flipbook.has("stretch_to_lifetime")) this.stretchFPS = flipbook.get("stretch_to_lifetime").getAsBoolean();
if (flipbook.has("loop")) this.loop = flipbook.get("loop").getAsBoolean();
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
JsonArray size = new JsonArray();
JsonObject uv = new JsonObject();
size.add(this.sizeW.toJson());
size.add(this.sizeH.toJson());
/* Adding "uv" properties */
uv.addProperty("texture_width", this.textureWidth);
uv.addProperty("texture_height", this.textureHeight);
if (!this.flipbook && !MolangExpression.isZero(this.uvX) || !MolangExpression.isZero(this.uvY))
{
JsonArray uvs = new JsonArray();
uvs.add(this.uvX.toJson());
uvs.add(this.uvY.toJson());
uv.add("uv", uvs);
}
if (!this.flipbook && !MolangExpression.isZero(this.uvW) || !MolangExpression.isZero(this.uvH))
{
JsonArray uvs = new JsonArray();
uvs.add(this.uvW.toJson());
uvs.add(this.uvH.toJson());
uv.add("uv_size", uvs);
}
/* Adding "flipbook" properties to "uv" */
if (this.flipbook)
{
JsonObject flipbook = new JsonObject();
if (!MolangExpression.isZero(this.uvX) || !MolangExpression.isZero(this.uvY))
{
JsonArray base = new JsonArray();
base.add(this.uvX.toJson());
base.add(this.uvY.toJson());
flipbook.add("base_UV", base);
}
if (!MolangExpression.isZero(this.uvW) || !MolangExpression.isZero(this.uvH))
{
JsonArray uvSize = new JsonArray();
uvSize.add(this.uvW.toJson());
uvSize.add(this.uvH.toJson());
flipbook.add("size_UV", uvSize);
}
if (this.stepX != 0 || this.stepY != 0)
{
JsonArray step = new JsonArray();
step.add(this.stepX);
step.add(this.stepY);
flipbook.add("step_UV", step);
}
if (this.fps != 0) flipbook.addProperty("frames_per_second", this.fps);
if (!MolangExpression.isZero(this.maxFrame)) flipbook.add("max_frame", this.maxFrame.toJson());
if (this.stretchFPS) flipbook.addProperty("stretch_to_lifetime", true);
if (this.loop) flipbook.addProperty("loop", true);
uv.add("flipbook", flipbook);
}
if (this.facing.isDirection)
{
JsonObject directionObj = new JsonObject();
if (this.customDirection)
{
directionObj.addProperty("mode", "custom");
if (this.directionX != MolangParser.ZERO || this.directionY != MolangParser.ZERO || this.directionZ != MolangParser.ZERO)
{
JsonArray directionArray = new JsonArray();
directionArray.add(this.directionX.toJson());
directionArray.add(this.directionY.toJson());
directionArray.add(this.directionZ.toJson());
directionObj.add("custom_direction", directionArray);
}
object.add("direction", directionObj);
}
else if (this.directionSpeedThreshhold != 0.01f)
{
directionObj.addProperty("mode", "derive_from_velocity");
directionObj.addProperty("min_speed_threshold", this.directionSpeedThreshhold);
object.add("direction", directionObj);
}
}
/* Add main properties */
object.add("size", size);
object.addProperty("facing_camera_mode", this.facing.id);
object.add("uv", uv);
return object;
}
@Override
public void preRender(BedrockEmitter emitter, float partialTicks)
{}
@Override
public void render(BedrockEmitter emitter, BedrockParticle particle, BufferBuilder builder, float partialTicks)
{
this.calculateUVs(particle, partialTicks);
/* Render the particle */
double px = Interpolations.lerp(particle.prevPosition.x, particle.position.x, partialTicks);
double py = Interpolations.lerp(particle.prevPosition.y, particle.position.y, partialTicks);
double pz = Interpolations.lerp(particle.prevPosition.z, particle.position.z, partialTicks);
float angle = Interpolations.lerp(particle.prevRotation, particle.rotation, partialTicks);
Vector3d pos = this.calculatePosition(emitter, particle, px, py, pz);
px = pos.x;
py = pos.y;
pz = pos.z;
/* Calculate the geometry for billboards using cool matrix math */
int light = emitter.getBrightnessForRender(partialTicks, px, py, pz);
int lightX = light >> 16 & 65535;
int lightY = light & 65535;
this.calculateFacing(emitter, particle, px, py, pz);
this.rotation.rotZ(angle / 180 * (float) Math.PI);
this.transform.mul(this.rotation);
this.transform.setTranslation(new Vector3f((float) px, (float) py, (float) pz));
for (Vector4f vertex : this.vertices)
{
this.transform.transform(vertex);
}
float u1 = this.u1 / (float) this.textureWidth;
float u2 = this.u2 / (float) this.textureWidth;
float v1 = this.v1 / (float) this.textureHeight;
float v2 = this.v2 / (float) this.textureHeight;
builder.pos(this.vertices[0].x, this.vertices[0].y, this.vertices[0].z).tex(u1, v1).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[1].x, this.vertices[1].y, this.vertices[1].z).tex(u2, v1).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[2].x, this.vertices[2].y, this.vertices[2].z).tex(u2, v2).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[3].x, this.vertices[3].y, this.vertices[3].z).tex(u1, v2).lightmap(lightX, lightY).color(particle.r, particle.g, particle.b, particle.a).endVertex();
}
protected void calculateFacing(BedrockEmitter emitter, BedrockParticle particle, double px, double py, double pz)
{
/* Calculate yaw and pitch based on the facing mode */
float cameraYaw = emitter.cYaw;
float cameraPitch = emitter.cPitch;
double cameraX = emitter.cX;
double cameraY = emitter.cY;
double cameraZ = emitter.cZ;
/* Flip width when frontal perspective mode */
if (emitter.perspective == 2)
{
this.w = -this.w;
}
/* In GUI renderer */
else if (emitter.perspective == 100 && !this.facing.isLookAt)
{
cameraYaw = 180 - cameraYaw;
this.w = -this.w;
this.h = -this.h;
}
if (this.facing.isLookAt && !this.facing.isDirection)
{
double dX = cameraX - px;
double dY = cameraY - py;
double dZ = cameraZ - pz;
double horizontalDistance = MathHelper.sqrt(dX * dX + dZ * dZ);
cameraYaw = 180 - (float) (MathHelper.atan2(dZ, dX) * (180D / Math.PI)) - 90.0F;
cameraPitch = (float) (-(MathHelper.atan2(dY, horizontalDistance) * (180D / Math.PI))) + 180;
}
if (this.facing.isDirection)
{
if (this.customDirection)
{
/* evaluate custom direction molang */
this.direction.x = (float) this.directionX.get();
this.direction.y = (float) this.directionY.get();
this.direction.z = (float) this.directionZ.get();
}
else if (particle.speed.lengthSquared() > this.directionSpeedThreshhold * this.directionSpeedThreshhold)
{
this.direction.set(particle.speed);
this.direction.normalize();
}
else
{
this.direction.set(1, 0, 0);
}
double lengthSq = this.direction.lengthSquared();
if (lengthSq < 0.0001)
{
this.direction.set(1, 0, 0);
}
else if (Math.abs(lengthSq - 1) > 0.0001)
{
this.direction.normalize();
}
}
this.calculateVertices(emitter, particle);
switch (this.facing)
{
case ROTATE_XYZ:
case LOOKAT_XYZ:
this.rotation.rotY((float) Math.toRadians(cameraYaw));
this.transform.mul(this.rotation);
this.rotation.rotX((float) Math.toRadians(cameraPitch));
this.transform.mul(this.rotation);
break;
case ROTATE_Y:
case LOOKAT_Y:
this.rotation.rotY((float) Math.toRadians(cameraYaw));
this.transform.mul(this.rotation);
break;
case EMITTER_YZ:
if (!GuiModelRenderer.isRendering())
{
this.rotation.rotZ((float) Math.toRadians(180));
this.transform.mul(this.rotation);
this.rotation.rotY((float) Math.toRadians(90));
this.transform.mul(this.rotation);
}
else
{
this.rotation.rotY((float) Math.toRadians(-90));
this.transform.mul(this.rotation);
}
break;
case EMITTER_XZ:
if (!GuiModelRenderer.isRendering())
{
this.rotation.rotX((float) Math.toRadians(90));
this.transform.mul(this.rotation);
}
else
{
this.rotation.rotZ((float) Math.toRadians(180));
this.transform.mul(this.rotation);
this.rotation.rotX((float) Math.toRadians(-90));
this.transform.mul(this.rotation);
}
break;
case EMITTER_XY:
if (!GuiModelRenderer.isRendering())
{
this.rotation.rotX((float) Math.toRadians(180));
this.transform.mul(this.rotation);
}
else
{
this.rotation.rotY((float) Math.toRadians(180));
this.transform.mul(this.rotation);
}
break;
case DIRECTION_X:
this.rotation.rotY((float) Math.toRadians(this.getYaw()));
this.transform.mul(this.rotation);
this.rotation.rotX((float) Math.toRadians(this.getPitch()));
this.transform.mul(this.rotation);
this.rotation.rotY((float) Math.toRadians(90));
this.transform.mul(this.rotation);
break;
case DIRECTION_Y:
this.rotation.rotY((float) Math.toRadians(this.getYaw()));
this.transform.mul(this.rotation);
this.rotation.rotX((float) Math.toRadians(this.getPitch() + 90));
this.transform.mul(this.rotation);
break;
case DIRECTION_Z:
this.rotation.rotY((float) Math.toRadians(this.getYaw()));
this.transform.mul(this.rotation);
this.rotation.rotX((float) Math.toRadians(this.getPitch()));
this.transform.mul(this.rotation);
break;
case LOOKAT_DIRECTION:
this.rotation.setIdentity();
this.rotation.rotY((float) Math.toRadians(this.getYaw()));
this.transform.mul(this.rotation);
this.rotation.rotX((float) Math.toRadians(this.getPitch() + 90));
this.transform.mul(this.rotation);
Vector3f cameraDir = new Vector3f(
(float) (cameraX - px),
(float) (cameraY - py),
(float) (cameraZ - pz));
Vector3f rotatedNormal = new Vector3f(0,0,1);
this.transform.transform(rotatedNormal);
/*
* The direction vector is the normal of the plane used for calculating the rotation around local y Axis.
* Project the cameraDir onto that plane to find out the axis angle (direction vector is the y axis).
*/
Vector3f projectDir = new Vector3f(this.direction);
projectDir.scale(cameraDir.dot(this.direction));
cameraDir.sub(projectDir);
if (cameraDir.lengthSquared() < 1.0e-30) break;
cameraDir.normalize();
/*
* The angle between two vectors is only between 0 and 180 degrees.
* RotationDirection will be parallel to direction but pointing in different directions depending
* on the rotation of cameraDir. Use this to find out the sign of the angle
* between cameraDir and the rotatedNormal.
*/
Vector3f rotationDirection = new Vector3f();
rotationDirection.cross(cameraDir, rotatedNormal);
this.rotation.rotY(-Math.copySign(cameraDir.angle(rotatedNormal), rotationDirection.dot(this.direction)));
this.transform.mul(this.rotation);
break;
default:
// Unknown facing mode
break;
}
}
/**
* @return the yaw angle in degrees of this {@link #direction}
*/
private float getYaw()
{
double yaw = Math.atan2(-this.direction.x, this.direction.z);
yaw = Math.toDegrees(yaw);
if (yaw < -180) {
yaw += 360;
} else if (yaw > 180) {
yaw -= 360;
}
return (float) -yaw;
}
/**
* @return the pitch angle in degrees of this {@link #direction}
*/
private float getPitch()
{
double pitch = Math.atan2(this.direction.y, Math.sqrt(this.direction.x * this.direction.x + this.direction.z * this.direction.z));
return (float) -Math.toDegrees(pitch);
}
protected void calculateVertices(BedrockEmitter emitter, BedrockParticle particle)
{
this.transform.setIdentity();
float hw = this.w * 0.5f;
float hh = this.h * 0.5f;
if (particle.relativeScaleBillboard)
{
hw *= emitter.scale[0];
hh *= emitter.scale[1];
}
this.vertices[0].set(-hw, -hh, 0, 1);
this.vertices[1].set( hw, -hh, 0, 1);
this.vertices[2].set( hw, hh, 0, 1);
this.vertices[3].set(-hw, hh, 0, 1);
}
protected Vector3d calculatePosition(BedrockEmitter emitter, BedrockParticle particle, double px, double py, double pz)
{
if (particle.relativePosition && particle.relativeRotation)
{
this.vector.set((float) px, (float) py, (float) pz);
if (particle.relativeScale)
{
Vector3d pos = new Vector3d(px, py, pz);
Matrix3d scale = new Matrix3d(emitter.scale[0], 0, 0,
0, emitter.scale[1], 0,
0, 0, emitter.scale[2]);
scale.transform(pos);
this.vector.x = (float) pos.x;
this.vector.y = (float) pos.y;
this.vector.z = (float) pos.z;
}
emitter.rotation.transform(this.vector);
px = this.vector.x;
py = this.vector.y;
pz = this.vector.z;
px += emitter.lastGlobal.x;
py += emitter.lastGlobal.y;
pz += emitter.lastGlobal.z;
}
else if (particle.relativeScale)
{
Vector3d pos = new Vector3d(px, py, pz);
Matrix3d scale = new Matrix3d(emitter.scale[0], 0, 0,
0, emitter.scale[1], 0,
0, 0, emitter.scale[2]);
pos.sub(emitter.lastGlobal); //transform back to local
scale.transform(pos);
pos.add(emitter.lastGlobal); //transform back to global
px = pos.x;
py = pos.y;
pz = pos.z;
}
return new Vector3d(px, py, pz);
}
@Override
public void renderOnScreen(BedrockParticle particle, int x, int y, float scale, float partialTicks)
{
this.calculateUVs(particle, partialTicks);
this.w = this.h = 0.5F;
float angle = Interpolations.lerp(particle.prevRotation, particle.rotation, partialTicks);
/* Calculate the geometry for billboards using cool matrix math */
float hw = this.w * 0.5f;
float hh = this.h * 0.5f;
this.vertices[0].set(-hw, -hh, 0, 1);
this.vertices[1].set( hw, -hh, 0, 1);
this.vertices[2].set( hw, hh, 0, 1);
this.vertices[3].set(-hw, hh, 0, 1);
this.transform.setIdentity();
this.transform.setScale(scale * 2.75F);
this.transform.setTranslation(new Vector3f(x, y - scale / 2, 0));
this.rotation.rotZ(angle / 180 * (float) Math.PI);
this.transform.mul(this.rotation);
for (Vector4f vertex : this.vertices)
{
this.transform.transform(vertex);
}
float u1 = this.u1 / (float) this.textureWidth;
float u2 = this.u2 / (float) this.textureWidth;
float v1 = this.v1 / (float) this.textureHeight;
float v2 = this.v2 / (float) this.textureHeight;
BufferBuilder builder = Tessellator.getInstance().getBuffer();
builder.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
builder.pos(this.vertices[0].x, this.vertices[0].y, this.vertices[0].z).tex(u1, v1).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[1].x, this.vertices[1].y, this.vertices[1].z).tex(u2, v1).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[2].x, this.vertices[2].y, this.vertices[2].z).tex(u2, v2).color(particle.r, particle.g, particle.b, particle.a).endVertex();
builder.pos(this.vertices[3].x, this.vertices[3].y, this.vertices[3].z).tex(u1, v2).color(particle.r, particle.g, particle.b, particle.a).endVertex();
Tessellator.getInstance().draw();
}
public void calculateUVs(BedrockParticle particle, float partialTicks)
{
/* Update particle's UVs and size */
this.w = (float) this.sizeW.get() * 2.25F;
this.h = (float) this.sizeH.get() * 2.25F;
float u = (float) this.uvX.get();
float v = (float) this.uvY.get();
float w = (float) this.uvW.get();
float h = (float) this.uvH.get();
if (this.flipbook)
{
int index = (int) (particle.getAge(partialTicks) * this.fps);
int max = (int) this.maxFrame.get();
if (this.stretchFPS)
{
float lifetime = (particle.lifetime <= 0) ? 0 : (particle.age + partialTicks) / (particle.lifetime);
//for particles with expiration - stretch differently since lifetime changed
if (particle.getExpireAge() != -1)
{
lifetime = (particle.lifetime <= 0) ? 0 : (particle.age + partialTicks) / (particle.getExpirationDelay());
}
index = (int) (lifetime * max);
}
if (this.loop && max != 0)
{
index = index % max;
}
if (index > max)
{
index = max;
}
u += this.stepX * index;
v += this.stepY * index;
}
this.u1 = u;
this.v1 = v;
this.u2 = u + w;
this.v2 = v + h;
}
@Override
public void postRender(BedrockEmitter emitter, float partialTicks)
{}
} | 27,602 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
Tint.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/appearance/Tint.java | package mchorse.blockbuster.client.particles.components.appearance;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import mchorse.blockbuster.client.particles.BedrockSchemeJsonAdapter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.functions.rounding.Round;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangValue;
import mchorse.mclib.utils.Interpolations;
import mchorse.mclib.utils.MathUtils;
import org.apache.commons.lang3.StringUtils;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public abstract class Tint
{
/**
* Parse a single color either in hex string format or JSON array
* (this should parse both RGB and RGBA expressions)
*/
public static Tint.Solid parseColor(JsonElement element, MolangParser parser) throws MolangException
{
MolangExpression r = MolangParser.ONE;
MolangExpression g = MolangParser.ONE;
MolangExpression b = MolangParser.ONE;
MolangExpression a = MolangParser.ONE;
if (element.isJsonPrimitive())
{
String hex = element.getAsString();
if (hex.startsWith("#") && (hex.length() == 7 || hex.length() == 9))
{
boolean hasAlpha = hex.length() == 9;
try
{
/* Apparently, Integer.parseInt() can't parse hex
* numbers that are longer than 6 hexadecimals... */
int color = Integer.parseInt(hex.substring(hasAlpha ? 3 : 1), 16);
float hr = (color >> 16 & 0xff) / 255F;
float hg = (color >> 8 & 0xff) / 255F;
float hb = (color & 0xff) / 255F;
float ha = hasAlpha ? Integer.parseInt(hex.substring(1, 3), 16) / 255F : 1;
r = new MolangValue(parser, new Constant(hr));
g = new MolangValue(parser, new Constant(hg));
b = new MolangValue(parser, new Constant(hb));
a = new MolangValue(parser, new Constant(ha));
}
catch (Exception e)
{}
}
}
else if (element.isJsonArray())
{
JsonArray array = element.getAsJsonArray();
if (array.size() == 3 || array.size() == 4)
{
r = parser.parseJson(array.get(0));
g = parser.parseJson(array.get(1));
b = parser.parseJson(array.get(2));
if (array.size() == 4)
{
a = parser.parseJson(array.get(3));
}
}
}
return new Tint.Solid(r, g, b, a);
}
/**
* Parse a gradient
*/
public static Tint parseGradient(JsonObject color, MolangParser parser) throws MolangException
{
JsonElement gradient = color.get("gradient");
MolangExpression expression = MolangParser.ZERO;
List<Tint.Gradient.ColorStop> colorStops = new ArrayList<Gradient.ColorStop>();
boolean equal = true;
if (gradient.isJsonObject())
{
for (Map.Entry<String, JsonElement> entry : gradient.getAsJsonObject().entrySet())
{
Tint.Solid stopColor = parseColor(entry.getValue(), parser);
colorStops.add(new Tint.Gradient.ColorStop(Float.parseFloat(entry.getKey()), stopColor));
}
colorStops.sort((a, b) -> Float.compare(a.stop, b.stop));
equal = false;
}
else if (gradient.isJsonArray())
{
JsonArray colors = gradient.getAsJsonArray();
int i = 0;
for (JsonElement stop : colors)
{
colorStops.add(new Tint.Gradient.ColorStop(i / (float) (colors.size() - 1), parseColor(stop, parser)));
i ++;
}
}
float range = colorStops.get(colorStops.size() - 1).stop;
for (Gradient.ColorStop stop : colorStops)
{
stop.stop /= range;
}
if (color.has("interpolant"))
{
expression = parser.parseJson(color.get("interpolant"));
}
return new Tint.Gradient(colorStops, range, expression, equal);
}
public abstract void compute(BedrockParticle particle);
public abstract JsonElement toJson();
/**
* Solid color (not necessarily static)
*/
public static class Solid extends Tint
{
public MolangExpression r;
public MolangExpression g;
public MolangExpression b;
public MolangExpression a;
public Solid(MolangExpression r, MolangExpression g, MolangExpression b, MolangExpression a)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
public Solid()
{
this.r = MolangParser.ONE;
this.g = MolangParser.ONE;
this.b = MolangParser.ONE;
this.a = MolangParser.ONE;
}
public boolean isConstant()
{
return MolangExpression.isExpressionConstant(this.r) && MolangExpression.isExpressionConstant(this.g)
&& MolangExpression.isExpressionConstant(this.b) && MolangExpression.isExpressionConstant(this.a);
}
@Override
public void compute(BedrockParticle particle)
{
particle.r = (float) this.r.get();
particle.g = (float) this.g.get();
particle.b = (float) this.b.get();
particle.a = (float) this.a.get();
}
@Override
public JsonElement toJson()
{
JsonArray array = new JsonArray();
if (MolangExpression.isOne(this.r) && MolangExpression.isOne(this.g) && MolangExpression.isOne(this.b) && MolangExpression.isOne(this.a))
{
return array;
}
array.add(this.r.toJson());
array.add(this.g.toJson());
array.add(this.b.toJson());
array.add(this.a.toJson());
return array;
}
public JsonElement toHexJson()
{
int r = (int) (this.r.get() * 255) & 0xff;
int g = (int) (this.g.get() * 255) & 0xff;
int b = (int) (this.b.get() * 255) & 0xff;
int a = (int) (this.a.get() * 255) & 0xff;
String hex = "#";
if (a < 255)
{
hex += StringUtils.leftPad(Integer.toHexString(a), 2, "0").toUpperCase();
}
hex += StringUtils.leftPad(Integer.toHexString(r), 2, "0").toUpperCase();
hex += StringUtils.leftPad(Integer.toHexString(g), 2, "0").toUpperCase();
hex += StringUtils.leftPad(Integer.toHexString(b), 2, "0").toUpperCase();
return new JsonPrimitive(hex);
}
public void lerp(BedrockParticle particle, float factor)
{
particle.r = Interpolations.lerp(particle.r, (float) this.r.get(), factor);
particle.g = Interpolations.lerp(particle.g, (float) this.g.get(), factor);
particle.b = Interpolations.lerp(particle.b, (float) this.b.get(), factor);
particle.a = Interpolations.lerp(particle.a, (float) this.a.get(), factor);
}
}
/**
* Gradient color, instead of using formulas, you can just specify a couple of colors
* and an expression at which color it would stop
*/
public static class Gradient extends Tint
{
public List<ColorStop> stops;
public MolangExpression interpolant;
public float range = 1;
public boolean equal;
public Gradient(List<ColorStop> stops, float range, MolangExpression interpolant, boolean equal)
{
this.stops = stops;
this.range = range;
this.interpolant = interpolant;
this.equal = equal;
}
public Gradient()
{
this.stops = new ArrayList<>();
this.stops.add(new ColorStop(0, new Tint.Solid(new MolangValue(null, new Constant(1F)), new MolangValue(null, new Constant(1F)), new MolangValue(null, new Constant(1F)), new MolangValue(null, new Constant(1F)))));
this.stops.add(new ColorStop(1, new Tint.Solid(new MolangValue(null, new Constant(0F)), new MolangValue(null, new Constant(0F)), new MolangValue(null, new Constant(0F)), new MolangValue(null, new Constant(1F)))));
this.interpolant = MolangParser.ZERO;
this.equal = false;
}
public void sort()
{
this.stops.sort((a, b) -> Float.compare(a.stop, b.stop));
}
@Override
public void compute(BedrockParticle particle)
{
int length = this.stops.size();
if (length == 0)
{
particle.r = particle.g = particle.b = particle.a = 1;
return;
}
else if (length == 1)
{
this.stops.get(0).color.compute(particle);
return;
}
double factor = this.interpolant.get();
factor = MathUtils.clamp(factor, 0, 1);
ColorStop prev = this.stops.get(0);
if (factor < prev.getStop(this.range))
{
prev.color.compute(particle);
return;
}
for (int i = 1; i < length; i ++)
{
ColorStop stop = this.stops.get(i);
if (stop.getStop(this.range) > factor)
{
prev.color.compute(particle);
stop.color.lerp(particle, (float) (factor - prev.getStop(this.range)) / (stop.getStop(this.range) - prev.getStop(this.range)));
return;
}
prev = stop;
}
prev.color.compute(particle);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
JsonElement color;
if (this.equal)
{
JsonArray gradient = new JsonArray();
for (ColorStop stop : this.stops)
{
gradient.add(stop.color.toHexJson());
}
color = gradient;
}
else
{
JsonObject gradient = new JsonObject();
for (ColorStop stop : this.stops)
{
gradient.add(String.valueOf(stop.getStop(this.range)), stop.color.toHexJson());
}
color = gradient;
}
if (!BedrockSchemeJsonAdapter.isEmpty(color))
{
object.add("gradient", color);
}
if (!MolangExpression.isZero(this.interpolant))
{
object.add("interpolant", this.interpolant.toJson());
}
return object;
}
public static class ColorStop
{
public float stop;
public Tint.Solid color;
public ColorStop(float stop, Tint.Solid color)
{
this.stop = stop;
this.color = color;
}
public float getStop(float range)
{
return this.stop * range;
}
}
}
} | 11,878 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentShapePoint.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/BedrockComponentShapePoint.java | package mchorse.blockbuster.client.particles.components.shape;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
public class BedrockComponentShapePoint extends BedrockComponentShapeBase
{
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
particle.position.x = (float) this.offset[0].get();
particle.position.y = (float) this.offset[1].get();
particle.position.z = (float) this.offset[2].get();
if (this.direction instanceof ShapeDirection.Vector)
{
this.direction.applyDirection(particle, particle.position.x, particle.position.y, particle.position.z);
}
}
} | 755 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ShapeDirection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/ShapeDirection.java | package mchorse.blockbuster.client.particles.components.shape;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import javax.vecmath.Vector3d;
public abstract class ShapeDirection
{
public static final ShapeDirection INWARDS = new Inwards(-1);
public static final ShapeDirection OUTWARDS = new Inwards(1);
public abstract void applyDirection(BedrockParticle particle, double x, double y, double z);
public abstract JsonElement toJson();
private static class Inwards extends ShapeDirection
{
private float factor;
public Inwards(float factor)
{
this.factor = factor;
}
@Override
public void applyDirection(BedrockParticle particle, double x, double y, double z)
{
Vector3d vector = new Vector3d(particle.position);
vector.sub(new Vector3d(x, y, z));
if (vector.length() <= 0)
{
vector.set(0, 0, 0);
}
else
{
vector.normalize();
vector.scale(this.factor);
}
particle.speed.set(vector);
}
@Override
public JsonElement toJson()
{
return new JsonPrimitive(this.factor < 0 ? "inwards" : "outwards");
}
}
public static class Vector extends ShapeDirection
{
public MolangExpression x;
public MolangExpression y;
public MolangExpression z;
public Vector(MolangExpression x, MolangExpression y, MolangExpression z)
{
this.x = x;
this.y = y;
this.z = z;
}
@Override
public void applyDirection(BedrockParticle particle, double x, double y, double z)
{
particle.speed.set((float) this.x.get(), (float) this.y.get(), (float) this.z.get());
if (particle.speed.length() <= 0)
{
particle.speed.set(0, 0, 0);
}
else
{
particle.speed.normalize();
}
}
@Override
public JsonElement toJson()
{
JsonArray array = new JsonArray();
array.add(this.x.toJson());
array.add(this.y.toJson());
array.add(this.z.toJson());
return array;
}
}
}
| 2,561 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentShapeEntityAABB.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/BedrockComponentShapeEntityAABB.java | package mchorse.blockbuster.client.particles.components.shape;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
public class BedrockComponentShapeEntityAABB extends BedrockComponentShapeBase
{
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
float centerX = (float) this.offset[0].get();
float centerY = (float) this.offset[1].get();
float centerZ = (float) this.offset[2].get();
float w = 0;
float h = 0;
float d = 0;
if (emitter.target != null)
{
w = emitter.target.width;
h = emitter.target.height;
d = emitter.target.width;
}
particle.position.x = centerX + ((float) Math.random() - 0.5F) * w;
particle.position.y = centerY + ((float) Math.random() - 0.5F) * h;
particle.position.z = centerZ + ((float) Math.random() - 0.5F) * d;
if (this.surface)
{
int roll = (int) (Math.random() * 6 * 100) % 6;
if (roll == 0) particle.position.x = centerX + w / 2F;
else if (roll == 1) particle.position.x = centerX - w / 2F;
else if (roll == 2) particle.position.y = centerY + h / 2F;
else if (roll == 3) particle.position.y = centerY - h / 2F;
else if (roll == 4) particle.position.z = centerZ + d / 2F;
else if (roll == 5) particle.position.z = centerZ - d / 2F;
}
this.direction.applyDirection(particle, centerX, centerY, centerZ);
}
}
| 1,622 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentShapeBox.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/BedrockComponentShapeBox.java | package mchorse.blockbuster.client.particles.components.shape;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentShapeBox extends BedrockComponentShapeBase
{
public MolangExpression[] halfDimensions = {MolangParser.ZERO, MolangParser.ZERO, MolangParser.ZERO};
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("half_dimensions"))
{
JsonArray array = element.getAsJsonArray("half_dimensions");
if (array.size() >= 3)
{
this.halfDimensions[0] = parser.parseJson(array.get(0));
this.halfDimensions[1] = parser.parseJson(array.get(1));
this.halfDimensions[2] = parser.parseJson(array.get(2));
}
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = (JsonObject) super.toJson();
JsonArray array = new JsonArray();
for (MolangExpression expression : this.halfDimensions)
{
array.add(expression.toJson());
}
object.add("half_dimensions", array);
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
float centerX = (float) this.offset[0].get();
float centerY = (float) this.offset[1].get();
float centerZ = (float) this.offset[2].get();
float w = (float) this.halfDimensions[0].get();
float h = (float) this.halfDimensions[1].get();
float d = (float) this.halfDimensions[2].get();
particle.position.x = centerX + ((float) Math.random() * 2 - 1F) * w;
particle.position.y = centerY + ((float) Math.random() * 2 - 1F) * h;
particle.position.z = centerZ + ((float) Math.random() * 2 - 1F) * d;
if (this.surface)
{
int roll = (int) (Math.random() * 6 * 100) % 6;
if (roll == 0) particle.position.x = centerX + w;
else if (roll == 1) particle.position.x = centerX - w;
else if (roll == 2) particle.position.y = centerY + h;
else if (roll == 3) particle.position.y = centerY - h;
else if (roll == 4) particle.position.z = centerZ + d;
else if (roll == 5) particle.position.z = centerZ - d;
}
this.direction.applyDirection(particle, centerX, centerY, centerZ);
}
} | 3,042 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentShapeSphere.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/BedrockComponentShapeSphere.java | package mchorse.blockbuster.client.particles.components.shape;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import javax.vecmath.Vector3f;
public class BedrockComponentShapeSphere extends BedrockComponentShapeBase
{
public MolangExpression radius = MolangParser.ZERO;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("radius")) this.radius = parser.parseJson(element.get("radius"));
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = (JsonObject) super.toJson();
if (!MolangExpression.isZero(this.radius)) object.add("radius", this.radius.toJson());
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
float centerX = (float) this.offset[0].get();
float centerY = (float) this.offset[1].get();
float centerZ = (float) this.offset[2].get();
float radius = (float) this.radius.get();
Vector3f direction = new Vector3f((float) Math.random() * 2 - 1, (float) Math.random() * 2 - 1, (float) Math.random() * 2 - 1);
direction.normalize();
if (!this.surface)
{
radius *= Math.random();
}
direction.scale(radius);
particle.position.x = centerX + direction.x;
particle.position.y = centerY + direction.y;
particle.position.z = centerZ + direction.z;
this.direction.applyDirection(particle, centerX, centerY, centerZ);
}
} | 2,142 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentShapeDisc.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/BedrockComponentShapeDisc.java | package mchorse.blockbuster.client.particles.components.shape;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import javax.vecmath.Matrix4f;
import javax.vecmath.Quat4f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
public class BedrockComponentShapeDisc extends BedrockComponentShapeSphere
{
public MolangExpression[] normal = {MolangParser.ZERO, MolangParser.ONE, MolangParser.ZERO};
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("plane_normal"))
{
JsonElement normal = element.get("plane_normal");
if (normal.isJsonPrimitive())
{
String axis = normal.getAsString().toLowerCase();
if (axis.equals("x"))
{
this.normal[0] = MolangParser.ONE;
this.normal[1] = MolangParser.ZERO;
}
else if (axis.equals("z"))
{
this.normal[1] = MolangParser.ZERO;
this.normal[2] = MolangParser.ONE;
}
}
else
{
JsonArray array = element.getAsJsonArray("plane_normal");
if (array.size() >= 3)
{
this.normal[0] = parser.parseJson(array.get(0));
this.normal[1] = parser.parseJson(array.get(1));
this.normal[2] = parser.parseJson(array.get(2));
}
}
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = (JsonObject) super.toJson();
JsonArray array = new JsonArray();
for (MolangExpression expression : this.normal)
{
array.add(expression.toJson());
}
object.add("plane_normal", array);
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
float centerX = (float) this.offset[0].get();
float centerY = (float) this.offset[1].get();
float centerZ = (float) this.offset[2].get();
Vector3f normal = new Vector3f((float) this.normal[0].get(), (float) this.normal[1].get(), (float) this.normal[2].get());
normal.normalize();
Quat4f quaternion = new Quat4f(normal.x, normal.y, normal.z, 1);
Matrix4f rotation = new Matrix4f();
rotation.set(quaternion);
Vector4f position = new Vector4f((float) Math.random() - 0.5F, 0, (float) Math.random() - 0.5F, 0);
position.normalize();
rotation.transform(position);
position.scale((float) (this.radius.get() * (this.surface ? 1 : Math.random())));
position.add(new Vector4f(centerX, centerY, centerZ, 0));
particle.position.x += position.x;
particle.position.y += position.y;
particle.position.z += position.z;
this.direction.applyDirection(particle, centerX, centerY, centerZ);
}
} | 3,647 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentShapeBase.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/shape/BedrockComponentShapeBase.java | package mchorse.blockbuster.client.particles.components.shape;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public abstract class BedrockComponentShapeBase extends BedrockComponentBase implements IComponentParticleInitialize
{
public MolangExpression[] offset = {MolangParser.ZERO, MolangParser.ZERO, MolangParser.ZERO};
public ShapeDirection direction = ShapeDirection.OUTWARDS;
public boolean surface = false;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("offset"))
{
JsonArray array = element.getAsJsonArray("offset");
if (array.size() >= 3)
{
this.offset[0] = parser.parseJson(array.get(0));
this.offset[1] = parser.parseJson(array.get(1));
this.offset[2] = parser.parseJson(array.get(2));
}
}
if (element.has("direction"))
{
JsonElement direction = element.get("direction");
if (direction.isJsonPrimitive())
{
String name = direction.getAsString();
if (name.equals("inwards")) this.direction = ShapeDirection.INWARDS;
else this.direction = ShapeDirection.OUTWARDS;
}
else if (direction.isJsonArray())
{
JsonArray array = direction.getAsJsonArray();
if (array.size() >= 3)
{
this.direction = new ShapeDirection.Vector(
parser.parseJson(array.get(0)),
parser.parseJson(array.get(1)),
parser.parseJson(array.get(2))
);
}
}
}
if (element.has("surface_only"))
{
this.surface = element.get("surface_only").getAsBoolean();
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
JsonArray offset = new JsonArray();
for (MolangExpression expression : this.offset)
{
offset.add(expression.toJson());
}
object.add("offset", offset);
if (this.direction != ShapeDirection.OUTWARDS)
{
object.add("direction", this.direction.toJson());
}
if (this.surface)
{
object.addProperty("surface_only", true);
}
return object;
}
} | 3,063 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentMotionDynamic.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/motion/BedrockComponentMotionDynamic.java | package mchorse.blockbuster.client.particles.components.motion;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentMotionDynamic extends BedrockComponentMotion implements IComponentParticleUpdate
{
public MolangExpression[] motionAcceleration = {MolangParser.ZERO, MolangParser.ZERO, MolangParser.ZERO};
public MolangExpression motionDrag = MolangParser.ZERO;
public MolangExpression rotationAcceleration = MolangParser.ZERO;
public MolangExpression rotationDrag = MolangParser.ZERO;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("linear_acceleration"))
{
JsonArray array = element.getAsJsonArray("linear_acceleration");
if (array.size() >= 3)
{
this.motionAcceleration[0] = parser.parseJson(array.get(0));
this.motionAcceleration[1] = parser.parseJson(array.get(1));
this.motionAcceleration[2] = parser.parseJson(array.get(2));
}
}
if (element.has("linear_drag_coefficient")) this.motionDrag = parser.parseJson(element.get("linear_drag_coefficient"));
if (element.has("rotation_acceleration")) this.rotationAcceleration = parser.parseJson(element.get("rotation_acceleration"));
if (element.has("rotation_drag_coefficient")) this.rotationDrag = parser.parseJson(element.get("rotation_drag_coefficient"));
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
JsonArray acceleration = new JsonArray();
for (MolangExpression expression : this.motionAcceleration)
{
acceleration.add(expression.toJson());
}
object.add("linear_acceleration", acceleration);
if (!MolangExpression.isZero(this.motionDrag)) object.add("linear_drag_coefficient", this.motionDrag.toJson());
if (!MolangExpression.isZero(this.rotationAcceleration)) object.add("rotation_acceleration", this.rotationAcceleration.toJson());
if (!MolangExpression.isZero(this.rotationDrag)) object.add("rotation_drag_coefficient", this.rotationDrag.toJson());
return object;
}
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
particle.acceleration.x += (float) this.motionAcceleration[0].get();
particle.acceleration.y += (float) this.motionAcceleration[1].get();
particle.acceleration.z += (float) this.motionAcceleration[2].get();
particle.drag = (float) this.motionDrag.get();
particle.rotationAcceleration += (float) this.rotationAcceleration.get() / 20F;
particle.rotationDrag = (float) this.rotationDrag.get();
}
} | 3,485 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentMotionCollision.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/motion/BedrockComponentMotionCollision.java | package mchorse.blockbuster.client.particles.components.motion;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.blockbuster.utils.EntityTransformationUtils;
import mchorse.mclib.math.Operation;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.utils.MathUtils;
import mchorse.metamorph.api.MorphUtils;
import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import javax.annotation.Nullable;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import java.util.HashMap;
import java.util.List;
public class BedrockComponentMotionCollision extends BedrockComponentBase implements IComponentParticleUpdate
{
public MolangExpression enabled = MolangParser.ONE;
public boolean preserveEnergy = false;
public boolean entityCollision;
public boolean momentum;
public float collisionDrag = 0;
public float bounciness = 1;
public float randomBounciness = 0;
public float randomDamp = 0;
public float damp = 0; // should be like in Blender
public int splitParticleCount;
public float splitParticleSpeedThreshold; // threshold to activate the split
public float radius = 0.01F;
public boolean expireOnImpact;
public MolangExpression expirationDelay = MolangParser.ZERO;
public boolean realisticCollision;
public boolean realisticCollisionDrag;
public float rotationCollisionDrag;
/* Runtime options */
private Vector3d previous = new Vector3d();
private Vector3d current = new Vector3d();
private BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
public static float getComponent(Vector3f vector, EnumFacing.Axis component)
{
if (component == EnumFacing.Axis.X)
{
return vector.x;
}
else if (component == EnumFacing.Axis.Y)
{
return vector.y;
}
return vector.z;
}
public static void setComponent(Vector3f vector, EnumFacing.Axis component, float value)
{
if (component == EnumFacing.Axis.X)
{
vector.x = value;
}
else if (component == EnumFacing.Axis.Y)
{
vector.y = value;
}
else
{
vector.z = value;
}
}
public static void negateComponent(Vector3f vector, EnumFacing.Axis component)
{
setComponent(vector, component, -getComponent(vector, component));
}
public static double getComponent(Vector3d vector, EnumFacing.Axis component)
{
if (component == EnumFacing.Axis.X)
{
return vector.x;
}
else if (component == EnumFacing.Axis.Y)
{
return vector.y;
}
return vector.z;
}
public static void setComponent(Vector3d vector, EnumFacing.Axis component, double value)
{
if (component == EnumFacing.Axis.X)
{
vector.x = value;
}
else if (component == EnumFacing.Axis.Y)
{
vector.y = value;
}
else
{
vector.z = value;
}
}
public static void negateComponent(Vector3d vector, EnumFacing.Axis component)
{
setComponent(vector, component, -getComponent(vector, component));
}
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("enabled")) this.enabled = parser.parseJson(element.get("enabled"));
if (element.has("entityCollision")) this.entityCollision = element.get("entityCollision").getAsBoolean();
if (element.has("momentum")) this.momentum = element.get("momentum").getAsBoolean();
if (element.has("realistic_collision_drag")) this.realisticCollisionDrag = element.get("realistic_collision_drag").getAsBoolean();
if (element.has("collision_drag")) this.collisionDrag = element.get("collision_drag").getAsFloat();
if (element.has("coefficient_of_restitution")) this.bounciness = element.get("coefficient_of_restitution").getAsFloat();
if (element.has("bounciness_randomness")) this.randomBounciness = element.get("bounciness_randomness").getAsFloat();
if (element.has("collision_rotation_drag")) this.rotationCollisionDrag = element.get("collision_rotation_drag").getAsFloat();
if (element.has("preserveEnergy") && element.get("preserveEnergy").isJsonPrimitive())
{
JsonPrimitive energy = element.get("preserveEnergy").getAsJsonPrimitive();
if (energy.isBoolean())
{
this.preserveEnergy = energy.getAsBoolean();
}
else
{
this.preserveEnergy = MolangExpression.isOne(parser.parseJson(energy));
}
}
if (element.has("damp")) this.damp = element.get("damp").getAsFloat();
if (element.has("random_damp")) this.randomDamp = element.get("random_damp").getAsFloat();
if (element.has("split_particle_count")) this.splitParticleCount = element.get("split_particle_count").getAsInt();
if (element.has("split_particle_speedThreshold")) this.splitParticleSpeedThreshold = element.get("split_particle_speedThreshold").getAsFloat();
if (element.has("collision_radius")) this.radius = element.get("collision_radius").getAsFloat();
if (element.has("expire_on_contact")) this.expireOnImpact = element.get("expire_on_contact").getAsBoolean();
if (element.has("expirationDelay")) this.expirationDelay = parser.parseJson(element.get("expirationDelay"));
if (element.has("realisticCollision")) this.realisticCollision = element.get("realisticCollision").getAsBoolean();
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (!MolangExpression.isOne(this.enabled)) object.add("enabled", this.enabled.toJson());
if (this.realisticCollision) object.addProperty("realisticCollision", true);
if (this.entityCollision) object.addProperty("entityCollision", true);
if (this.momentum) object.addProperty("momentum", true);
if (this.realisticCollisionDrag) object.addProperty("realistic_collision_drag", true);
if (this.collisionDrag != 0) object.addProperty("collision_drag", this.collisionDrag);
if (this.bounciness != 1) object.addProperty("coefficient_of_restitution", this.bounciness);
if (this.rotationCollisionDrag != 0) object.addProperty("collision_rotation_drag", this.rotationCollisionDrag);
if (this.randomBounciness != 0) object.addProperty("bounciness_randomness", this.randomBounciness);
if (this.preserveEnergy) object.addProperty("preserveEnergy", this.preserveEnergy);
if (this.damp != 0) object.addProperty("damp", this.damp);
if (this.randomDamp != 0) object.addProperty("random_damp", this.randomDamp);
if (this.splitParticleCount != 0) object.addProperty("split_particle_count", this.splitParticleCount);
if (this.splitParticleSpeedThreshold != 0) object.addProperty("split_particle_speedThreshold", this.splitParticleSpeedThreshold);
if (this.radius != 0.01F) object.addProperty("collision_radius", this.radius);
if (this.expireOnImpact) object.addProperty("expire_on_contact", true);
if (!MolangExpression.isZero(this.expirationDelay)) object.add("expirationDelay", this.expirationDelay.toJson());
return object;
}
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
particle.realisticCollisionDrag = this.realisticCollisionDrag;
if (emitter.world == null)
{
return;
}
float r = this.radius;
this.previous.set(particle.getGlobalPosition(emitter, particle.prevPosition));
this.current.set(particle.getGlobalPosition(emitter));
Vector3d prev = this.previous;
Vector3d now = this.current;
double x = now.x - prev.x;
double y = now.y - prev.y;
double z = now.z - prev.z;
boolean veryBig = Math.abs(x) > 10 || Math.abs(y) > 10 || Math.abs(z) > 10;
this.pos.setPos(now.x, now.y, now.z);
if (veryBig || !emitter.world.isBlockLoaded(this.pos))
{
return;
}
AxisAlignedBB aabb = new AxisAlignedBB(prev.x - r, prev.y - r, prev.z - r, prev.x + r, prev.y + r, prev.z + r);
double d0 = y;
double origX = x;
double origZ = z;
List<Entity> entities = emitter.world.getEntitiesWithinAABB(Entity.class, aabb.expand(x, y, z));
HashMap<Entity, AxisAlignedBB> entityAABBs = new HashMap<Entity, AxisAlignedBB>();
HashMap<Entity, CollisionOffset> staticEntityAABBs = new HashMap<>(); //for newtons first law
/* for own hitbox implementation: check for hitbox expanded for the previous position - prevent fast moving tunneling */
List<AxisAlignedBB> list = emitter.world.getCollisionBoxes(null, aabb.expand(x, y, z));
if ((!list.isEmpty() || (!entities.isEmpty() && this.entityCollision)) && !particle.intersected)
{
particle.firstIntersection = particle.age;
particle.intersected = true;
}
if (!particle.manual && !Operation.equals(this.enabled.get(), 0))
{
if (this.entityCollision)
{
for (Entity entity : entities)
{
AxisAlignedBB aabb2 = new AxisAlignedBB(prev.x - r, prev.y - r, prev.z - r, prev.x + r, prev.y + r, prev.z + r);
AxisAlignedBB entityAABB = entity.getEntityBoundingBox();
double y2 = y, x2 = x, z2 = z;
y2 = entityAABB.calculateYOffset(aabb2, y2);
aabb2 = aabb2.offset(0.0D, y2, 0.0D);
x2 = entityAABB.calculateXOffset(aabb2, x2);
aabb2 = aabb2.offset(x2, 0.0D, 0.0D);
z2 = entityAABB.calculateZOffset(aabb2, z2);
aabb2 = aabb2.offset(0.0D, 0.0D, z2);
if (d0 == y2 && origX == x2 && origZ == z2)
{
entityAABBs.put(entity, entityAABB); //Note to myself: maybe start already here with collision response?
}
else
{
list.add(entityAABB);
staticEntityAABBs.put(entity, new CollisionOffset(entityAABB, x2, y2, z2));
if (this.momentum && d0 == y2)
{
momentum(particle,entity);
}
}
}
}
CollisionOffset offsetData = calculateOffsets(aabb, list, x, y, z);
aabb = offsetData.aabb;
x = offsetData.x;
y = offsetData.y;
z = offsetData.z;
if (d0 != y || origX != x || origZ != z)
{
this.collision(particle, emitter, prev);
now.set(aabb.minX + r, aabb.minY + r, aabb.minZ + r);
if (d0 != y)
{
if (d0 < y) now.y = aabb.minY;
else now.y = aabb.maxY;
now.y += d0 < y ? r : -r;
this.collisionHandler(particle, emitter, EnumFacing.Axis.Y, now, prev);
/* here comes inertia */
/* remove unecessary elements from collisionTime*/
particle.entityCollisionTime.keySet().retainAll(staticEntityAABBs.keySet());
for (HashMap.Entry<Entity, CollisionOffset> entry : staticEntityAABBs.entrySet())
{
CollisionOffset offsetData2 = entry.getValue();
AxisAlignedBB entityAABB = offsetData2.aabb;
Entity collidingEntity = entry.getKey();
if (d0 != offsetData2.y && origX == offsetData2.x && origZ == offsetData2.z)
{
inertia(particle, collidingEntity, now);
}
if (particle.entityCollisionTime.containsKey(collidingEntity))
{
particle.entityCollisionTime.get(collidingEntity).y = particle.age;
}
else
{
particle.entityCollisionTime.put(entry.getKey(), new Vector3f(-1F, particle.age, -1F));
}
}
}
if (origX != x)
{
if (origX < x) now.x = aabb.minX;
else now.x = aabb.maxX;
now.x += origX < x ? r : -r;
collisionHandler(particle, emitter, EnumFacing.Axis.X, now, prev);
}
if (origZ != z)
{
if (origZ < z) now.z = aabb.minZ;
else now.z = aabb.maxZ;
now.z += origZ < z ? r : -r;
collisionHandler(particle, emitter, EnumFacing.Axis.Z, now, prev);
}
particle.position.set(now);
drag(particle);
}
else if (entityAABBs.isEmpty() && this.realisticCollisionDrag) //no collision - reset collision drag
{
particle.dragFactor = 0;
}
else
{
particle.rotationCollisionDrag = 0;
}
for (HashMap.Entry<Entity, AxisAlignedBB> entry : entityAABBs.entrySet())
{
AxisAlignedBB entityAABB = entry.getValue();
Entity entity = entry.getKey();
Vector3f speedEntity = new Vector3f((float) (entity.posX - entity.prevPosX), (float) (entity.posY - entity.prevPosY), (float) (entity.posZ - entity.prevPosZ));
Vector3f ray;
if (speedEntity.x != 0 || speedEntity.y != 0 || speedEntity.z != 0)
{
ray = speedEntity;
}
else
{
/* fixes the issue of particles falling through the entity
* when they lie on the surface while the hitbox changes
* downside: the position is not always accurate depending on the movement*/
/*Vector3f particleMotion = new Vector3f();
particleMotion.x = (float) (particle.prevPosition.x - particle.position.x);
particleMotion.y = (float) (particle.prevPosition.y - particle.position.y);
particleMotion.z = (float) (particle.prevPosition.z - particle.position.z);
ray = particleMotion;*/
continue;
}
Vector3d frac = intersect(ray, particle.getGlobalPosition(emitter), entityAABB);
if (frac != null)
{
particle.position.add(frac);
AxisAlignedBB aabb2 = new AxisAlignedBB(particle.position.x - r, particle.position.y - r, particle.position.z - r, particle.position.x + r, particle.position.y + r, particle.position.z + r);
collision(particle, emitter, prev);
if ((aabb2.minX < entityAABB.maxX && aabb2.maxX > entityAABB.maxX) || (aabb2.maxX > entityAABB.minX && aabb2.minX < entityAABB.minX))
{
entityCollision(particle, emitter, entity, EnumFacing.Axis.X, prev);
}
if ((aabb2.minY < entityAABB.maxY && aabb2.maxY > entityAABB.maxY) || (aabb2.maxY > entityAABB.minY && aabb2.minY < entityAABB.minY))
{
entityCollision(particle, emitter, entity, EnumFacing.Axis.Y, prev);
}
if ((aabb2.minZ < entityAABB.maxZ && aabb2.maxZ > entityAABB.maxZ) || (aabb2.maxZ > entityAABB.minZ && aabb2.minZ < entityAABB.minZ))
{
entityCollision(particle, emitter, entity, EnumFacing.Axis.Z, prev);
}
}
}
if (!entityAABBs.isEmpty())
{
this.drag(particle);
}
}
}
public void collision(BedrockParticle particle, BedrockEmitter emitter, Vector3d prev)
{
if (this.expireOnImpact)
{
double expirationDelay = this.expirationDelay.get();
if (expirationDelay != 0 && !particle.collided)
{
particle.setExpirationDelay(expirationDelay);
}
else if (expirationDelay == 0 && !particle.collided)
{
particle.dead = true;
return;
}
}
if (particle.relativePosition)
{
particle.relativePosition = false;
particle.prevPosition.set(prev);
}
particle.rotationCollisionDrag = this.rotationCollisionDrag;
particle.collided = true;
}
public void entityCollision(BedrockParticle particle, BedrockEmitter emitter, Entity entity, EnumFacing.Axis component, Vector3d prev)
{
Vector3f entitySpeed = new Vector3f((float) (entity.posX - entity.prevPosX), (float) (entity.posY - entity.prevPosY), (float) (entity.posZ - entity.prevPosZ));
Vector3d entityPosition = new Vector3d(entity.posX, entity.posY,entity.posZ);
if (this.momentum)
{
momentum(particle,entity);
}
/* collisionTime should be not changed - otherwise the particles will stop when moving against moving entites */
float tmpTime = getComponent(particle.collisionTime, component);
double delta = getComponent(particle.position, component) - getComponent(entityPosition, component);
setComponent(particle.position, component, getComponent(particle.position, component) + (delta > 0 ? this.radius : -this.radius));
collisionHandler(particle, emitter, component, particle.position, prev);
/* collisionTime should not change or otherwise particles will lose their speed although they should be reflected */
setComponent(particle.collisionTime, component, tmpTime);
if (delta > 0 && component == EnumFacing.Axis.Y) //particle is above
{
inertia(particle, entity, null);
}
/* particle speed is always switched (realistcCollision==true), as it always collides with the entity, but it should only have one correct direction */
if (getComponent(particle.speed, component) > 0)
{
if (getComponent(entitySpeed, component) < 0) negateComponent(particle.speed, component);
}
else if (getComponent(particle.speed, component) < 0)
{
if (getComponent(entitySpeed, component) > 0) negateComponent(particle.speed, component);
}
/* otherwise particles would stick on the body and get reflected when entity stops */
/* note to myself: when particle lies on top and you fly up it floats weirdly - need to redo this system a little bit*/
setComponent(particle.position, component, getComponent(particle.position, component) + getComponent(particle.speed, component) / 20F);
}
public void collisionHandler(BedrockParticle particle, BedrockEmitter emitter, EnumFacing.Axis component, Vector3d now, Vector3d prev)
{
float collisionTime = getComponent(particle.collisionTime, component);
float speed = getComponent(particle.speed, component);
float accelerationFactor = getComponent(particle.accelerationFactor, component);
/* realistic collision */
if (this.realisticCollision)
{
if (collisionTime != (particle.age - 1))
{
if (this.bounciness != 0)
{
setComponent(particle.speed, component, -speed * this.bounciness);
}
}
else if (collisionTime == (particle.age - 1))
{
setComponent(particle.speed, component, 0); //particle laid on that surface since last tick
}
}
else
{
setComponent(particle.accelerationFactor, component, accelerationFactor * -this.bounciness);
}
if (collisionTime != (particle.age - 1))
{
/* random bounciness */
if (this.randomBounciness != 0 /* && Math.round(particle.speed.x) != 0 */)
{
particle.speed = this.randomBounciness(particle.speed, component, this.randomBounciness);
}
/* split particles */
if (this.splitParticleCount != 0)
{
this.splitParticle(particle, emitter, component, now, prev);
}
/* damping */
if (damp != 0)
{
particle.speed = this.damping(particle.speed);
}
}
if (collisionTime != particle.age - 1)
{
particle.bounces++;
}
setComponent(particle.collisionTime, component, particle.age);
}
public void inertia(BedrockParticle particle, Entity entity, @Nullable Vector3d now)
{
if (this.collisionDrag==0)
{
return;
}
Vector3d entitySpeed = new Vector3d((entity.posX - entity.prevPosX), (entity.posY - entity.prevPosY), (entity.posZ - entity.prevPosZ));
double prevPrevPosX = EntityTransformationUtils.getPrevPrevPosX(entity);
double prevPrevPosY = EntityTransformationUtils.getPrevPrevPosY(entity);
double prevPrevPosZ = EntityTransformationUtils.getPrevPrevPosZ(entity);
Vector3d prevEntitySpeed = new Vector3d(entity.prevPosX-prevPrevPosX, entity.prevPosY-prevPrevPosY, entity.prevPosZ-prevPrevPosZ);
/*if (Math.round((prevEntitySpeed.x-entitySpeed.x)*1000D) != 0 || Math.round((prevEntitySpeed.y-entitySpeed.y)*1000D) != 0 || Math.round((prevEntitySpeed.z-entitySpeed.z)*1000D) != 0)
{
particle.dragFactor = 0;
}*/
/* for first collision from the inertial system of the particle it is acceleration from zero to current velocity */
if (!particle.entityCollisionTime.containsKey(entity))
{
prevEntitySpeed.scale(0);
}
else
{
/* stick the particle on top of the entity */
particle.offset.x = entitySpeed.x;
particle.offset.z = entitySpeed.z;
if (now==null)
{
particle.position.x += entitySpeed.x;
particle.position.z += entitySpeed.z;
}
else
{
now.x += entitySpeed.x;
now.z += entitySpeed.z;
}
}
particle.speed.x += Math.round((prevEntitySpeed.x-entitySpeed.x)*1000D)/250D; //scale it up so it gets more noticable
particle.speed.y += Math.round((prevEntitySpeed.y-entitySpeed.y)*1000D)/250D;
particle.speed.z += Math.round((prevEntitySpeed.z-entitySpeed.z)*1000D)/250D;
}
public void momentum(BedrockParticle particle, Entity entity)
{
particle.speed.x += 2 * (entity.posX - entity.prevPosX);
particle.speed.y += 2 * (entity.posY - entity.prevPosY);
particle.speed.z += 2 * (entity.posZ - entity.prevPosZ);
}
public void drag(BedrockParticle particle)
{
/* only apply drag when speed is almost not zero and randombounciness and realisticCollision are off
* prevent particles from accelerating away when randomBounciness is active */
if (!((this.randomBounciness != 0 || this.realisticCollision) && Math.round(particle.speed.x*10000) == 0 && Math.round(particle.speed.y*10000) == 0 && Math.round(particle.speed.z*10000) == 0))
{
particle.dragFactor = this.collisionDrag;
/*if (this.realisticCollisionDrag)
{
//TODO WTF IS THIS
particle.dragFactor = 3*this.collisionDrag;
}
else
{
//why is it adding it on top of the old drag?
particle.dragFactor += this.collisionDrag;
}*/
}
}
public Vector3f damping(Vector3f vector)
{
float random = (float) (this.randomDamp * (Math.random() * 2 - 1));
float clampedValue = MathUtils.clamp((1 - this.damp) + random, 0, 1);
vector.scale(clampedValue);
return vector;
}
public void splitParticle(BedrockParticle particle, BedrockEmitter emitter, EnumFacing.Axis component, Vector3d now, Vector3d prev)
{
float speed = getComponent(particle.speed, component);
if (!(Math.abs(speed) > Math.abs(this.splitParticleSpeedThreshold)))
{
return;
}
for (int i = 0; i < this.splitParticleCount; i++)
{
BedrockParticle splitParticle = emitter.createParticle(false);
particle.softCopy(splitParticle);
splitParticle.position.set(now);
splitParticle.prevPosition.set(prev);
splitParticle.morph.setDirect(MorphUtils.copy(particle.morph.get()));
splitParticle.bounces = 1;
double splitPosition = getComponent(splitParticle.position, component);
setComponent(splitParticle.collisionTime, component, particle.age);
setComponent(splitParticle.position, component, splitPosition/* + ((orig < offset) ? this.radius : -this.radius)*/);
Vector3f randomSpeed = this.randomBounciness(particle.speed, component, (this.randomBounciness != 0) ? this.randomBounciness : 10);
randomSpeed.scale(1.0f / this.splitParticleCount);
splitParticle.speed.set(randomSpeed);
if (this.damp != 0)
{
splitParticle.speed = this.damping(splitParticle.speed);
}
emitter.splitParticles.add(splitParticle);
}
particle.dead = true;
}
public Vector3f randomBounciness(Vector3f vector0, EnumFacing.Axis component, float randomness)
{
if (randomness != 0)
{
/* don't change the vector0 - pointer behaviour not wanted here */
Vector3f vector = new Vector3f(vector0);
/* scale down the vector components not involved in the collision reflection */
float randomfactor = 0.25F;
float prevLength = vector.length();
randomness *= 0.1F;
float random1 = (float) Math.random() * randomness;
float random2 = (float) (randomness * randomfactor * (Math.random() * 2 - 1));
float random3 = (float) (randomness * randomfactor * (Math.random() * 2 - 1));
float vectorValue = getComponent(vector, component);
if (component == EnumFacing.Axis.X)
{
vector.y += random2;
vector.z += random3;
}
else if (component == EnumFacing.Axis.Y)
{
vector.x += random2;
vector.z += random3;
}
else
{
vector.y += random2;
vector.x += random3;
}
if (this.bounciness != 0)
{
setComponent(vector, component, vectorValue + ((vectorValue < 0) ? -random1 : random1));
vector.scale(prevLength / vector.length()); //scale back to original length
}
else if (vector.x != 0 || vector.y != 0 || vector.z != 0)
{
/* if bounciness=0 then the speed of a specific component wont't affect the particles movement
* so the particles speed needs to be scaled back without taking that component into account
* when bounciness=0 the energy of that component gets absorbed by the collision block and therefore is lost for the particle
*/
if (this.preserveEnergy)
{
setComponent(vector, component, 0);
}
/* if the vector is now zero... don't execute 1/vector.length() -> 1/0 not possible */
if (vector.x != 0 || vector.y != 0 || vector.z != 0)
{
vector.scale(prevLength / vector.length());
}
setComponent(vector, component, vectorValue);
}
else /* bounciness == 0 and vector is zero (rare case, but not impossible) */
{
/* if you don't want particles to stop, while others randomly slide away,
* when bounciness==0, then return vector0 */
return vector0;
}
return vector;
}
return vector0;
}
public Vector3d intersect(Vector3f ray, Vector3d orig, AxisAlignedBB aabb)
{
double tmin = (aabb.minX - orig.x) / ray.x;
double tmax = (aabb.maxX - orig.x) / ray.x;
if (tmin > tmax)
{
double tminTmp = tmin;
tmin = tmax;
tmax = tminTmp;
}
double tymin = (aabb.minY - orig.y) / ray.y;
double tymax = (aabb.maxY - orig.y) / ray.y;
if (tymin > tymax)
{
double tyminTmp = tymin;
tymin = tymax;
tymax = tyminTmp;
}
if (tmin > tymax || tymin > tmax)
return null;
if (tymin > tmin)
tmin = tymin;
if (tymax < tmax)
tmax = tymax;
double tzmin = (aabb.minZ - orig.z) / ray.z;
double tzmax = (aabb.maxZ - orig.z) / ray.z;
if (tzmin > tzmax)
{
double tzminTmp = tzmin;
tzmin = tzmax;
tzmax = tzminTmp;
}
if (tmin > tzmax || tzmin > tmax)
return null;
if (tzmax < tmax)
tmax = tzmax;
Vector3d ray1 = new Vector3d(ray);
ray1.scale(tmax);
return ray1;
}
/**
* @param aabb AxisAlignedBoundingBox of the main aabb
* @param list List of AxisAlignedBoundingBoxs of the targets
* @param x origin
* @param y origin
* @param z origin
* @return CollisionOffset which includes aabb, x, y, z
*/
public CollisionOffset calculateOffsets(AxisAlignedBB aabb, List<AxisAlignedBB> list, double x, double y, double z)
{
for (AxisAlignedBB axisalignedbb : list)
{
y = axisalignedbb.calculateYOffset(aabb, y);
}
aabb = aabb.offset(0.0D, y, 0.0D);
for (AxisAlignedBB axisalignedbb1 : list)
{
x = axisalignedbb1.calculateXOffset(aabb, x);
}
aabb = aabb.offset(x, 0.0D, 0.0D);
for (AxisAlignedBB axisalignedbb2 : list)
{
z = axisalignedbb2.calculateZOffset(aabb, z);
}
aabb = aabb.offset(0.0D, 0.0D, z);
return new CollisionOffset(aabb, x, y, z);
}
@Override
public int getSortingIndex()
{
return 50;
}
public class CollisionOffset
{
public AxisAlignedBB aabb;
public double x;
public double y;
public double z;
public CollisionOffset(AxisAlignedBB aabb, double x, double y, double z)
{
this.aabb = aabb;
this.x = x;
this.y = y;
this.z = z;
}
}
}
| 32,501 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentInitialSpeed.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/motion/BedrockComponentInitialSpeed.java | package mchorse.blockbuster.client.particles.components.motion;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentInitialSpeed extends BedrockComponentBase implements IComponentParticleInitialize
{
public MolangExpression speed = MolangParser.ONE;
public MolangExpression[] direction;
@Override
public BedrockComponentBase fromJson(JsonElement element, MolangParser parser) throws MolangException
{
if (element.isJsonArray())
{
JsonArray array = element.getAsJsonArray();
if (array.size() >= 3)
{
this.direction = new MolangExpression[] {parser.parseJson(array.get(0)), parser.parseJson(array.get(1)), parser.parseJson(array.get(2))};
}
}
else if (element.isJsonPrimitive())
{
this.speed = parser.parseJson(element);
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
if (this.direction != null)
{
JsonArray array = new JsonArray();
for (MolangExpression expression : this.direction)
{
array.add(expression.toJson());
}
return array;
}
return this.speed.toJson();
}
@Override
public boolean canBeEmpty()
{
return true;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
if (this.direction != null)
{
particle.speed.set(
(float) this.direction[0].get(),
(float) this.direction[1].get(),
(float) this.direction[2].get()
);
}
else
{
float speed = (float) this.speed.get();
particle.speed.scale(speed);
}
}
@Override
public int getSortingIndex()
{
return 5;
}
} | 2,430 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentInitialSpin.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/motion/BedrockComponentInitialSpin.java | package mchorse.blockbuster.client.particles.components.motion;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
public class BedrockComponentInitialSpin extends BedrockComponentBase implements IComponentParticleInitialize
{
public MolangExpression rotation = MolangParser.ZERO;
public MolangExpression rate = MolangParser.ZERO;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("rotation")) this.rotation = parser.parseJson(element.get("rotation"));
if (element.has("rotation_rate")) this.rate = parser.parseJson(element.get("rotation_rate"));
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (!MolangExpression.isZero(this.rotation)) object.add("rotation", this.rotation.toJson());
if (!MolangExpression.isZero(this.rate)) object.add("rotation_rate", this.rate.toJson());
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
particle.initialRotation = (float) this.rotation.get();
particle.rotationVelocity = (float) this.rate.get() / 20;
}
} | 1,882 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentMotionParametric.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/motion/BedrockComponentMotionParametric.java | package mchorse.blockbuster.client.particles.components.motion;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.components.IComponentParticleUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import javax.vecmath.Vector3f;
public class BedrockComponentMotionParametric extends BedrockComponentMotion implements IComponentParticleInitialize, IComponentParticleUpdate
{
public MolangExpression[] position = {MolangParser.ZERO, MolangParser.ZERO, MolangParser.ZERO};
public MolangExpression rotation = MolangParser.ZERO;
@Override
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("relative_position") && element.get("relative_position").isJsonArray())
{
JsonArray array = element.get("relative_position").getAsJsonArray();
this.position[0] = parser.parseJson(array.get(0));
this.position[1] = parser.parseJson(array.get(1));
this.position[2] = parser.parseJson(array.get(2));
}
if (element.has("rotation"))
{
this.rotation = parser.parseJson(element.get("rotation"));
}
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
JsonArray position = new JsonArray();
for (MolangExpression expression : this.position)
{
position.add(expression.toJson());
}
object.add("relative_position", position);
if (!MolangExpression.isZero(this.rotation)) object.add("rotation", this.rotation.toJson());
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
Vector3f position = new Vector3f((float) this.position[0].get(), (float) this.position[1].get(), (float) this.position[2].get());
particle.manual = true;
particle.initialPosition.set(particle.position);
particle.matrix.transform(position);
particle.position.x = particle.initialPosition.x + position.x;
particle.position.y = particle.initialPosition.y + position.y;
particle.position.z = particle.initialPosition.z + position.z;
particle.rotation = (float) this.rotation.get();
}
@Override
public void update(BedrockEmitter emitter, BedrockParticle particle)
{
Vector3f position = new Vector3f((float) this.position[0].get(), (float) this.position[1].get(), (float) this.position[2].get());
particle.matrix.transform(position);
particle.position.x = particle.initialPosition.x + position.x;
particle.position.y = particle.initialPosition.y + position.y;
particle.position.z = particle.initialPosition.z + position.z;
particle.rotation = (float) this.rotation.get();
}
@Override
public int getSortingIndex()
{
return 10;
}
} | 3,599 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentMotion.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/motion/BedrockComponentMotion.java | package mchorse.blockbuster.client.particles.components.motion;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
public abstract class BedrockComponentMotion extends BedrockComponentBase
{} | 219 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentLocalSpace.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/meta/BedrockComponentLocalSpace.java | package mchorse.blockbuster.client.particles.components.meta;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentParticleInitialize;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.particles.emitter.BedrockParticle;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
public class BedrockComponentLocalSpace extends BedrockComponentBase implements IComponentParticleInitialize
{
public boolean position;
public boolean rotation;
public boolean scale;
public boolean scaleBillboard;
public boolean direction;
public boolean acceleration;
public boolean gravity;
public float linearVelocity;
public float angularVelocity;
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("position")) this.position = element.get("position").getAsBoolean();
if (element.has("rotation")) this.rotation = element.get("rotation").getAsBoolean();
if (element.has("scale")) this.scale = element.get("scale").getAsBoolean();
if (element.has("scale_billboard")) this.scaleBillboard = element.get("scale_billboard").getAsBoolean();
if (element.has("direction")) this.direction = element.get("direction").getAsBoolean();
if (element.has("acceleration")) this.acceleration = element.get("acceleration").getAsBoolean();
if (element.has("gravity")) this.gravity = element.get("gravity").getAsBoolean();
if (element.has("linear_velocity")) this.linearVelocity = element.get("linear_velocity").getAsFloat();
if (element.has("angular_velocity")) this.angularVelocity = element.get("angular_velocity").getAsFloat();
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (this.position) object.addProperty("position", true);
if (this.rotation) object.addProperty("rotation", true);
if (this.scale) object.addProperty("scale", true);
if (this.scaleBillboard) object.addProperty("scale_billboard", true);
if (this.direction) object.addProperty("direction", true);
if (this.acceleration) object.addProperty("acceleration", true);
if (this.gravity) object.addProperty("gravity", true);
if (this.linearVelocity!=0) object.addProperty("linear_velocity", this.linearVelocity);
if (this.angularVelocity!=0) object.addProperty("angular_velocity", this.angularVelocity);
return object;
}
@Override
public void apply(BedrockEmitter emitter, BedrockParticle particle)
{
particle.relativePosition = this.position;
particle.relativeRotation = this.rotation;
particle.relativeScale = this.scale;
particle.relativeScaleBillboard = this.scaleBillboard;
particle.relativeDirection = this.direction;
particle.relativeAcceleration = this.acceleration;
particle.gravity = this.gravity;
particle.linearVelocity = this.linearVelocity;
particle.angularVelocity = this.angularVelocity;
particle.setupMatrix(emitter);
}
@Override
public int getSortingIndex()
{
return 6;
}
}
| 3,602 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BedrockComponentInitialization.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/particles/components/meta/BedrockComponentInitialization.java | package mchorse.blockbuster.client.particles.components.meta;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import mchorse.blockbuster.client.particles.components.IComponentEmitterInitialize;
import mchorse.blockbuster.client.particles.components.IComponentEmitterUpdate;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.mclib.math.IValue;
import mchorse.mclib.math.molang.MolangException;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangAssignment;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangMultiStatement;
import java.util.Map;
public class BedrockComponentInitialization extends BedrockComponentBase implements IComponentEmitterInitialize, IComponentEmitterUpdate
{
/* Standard BedrockEdition variables - global inside an emitter */
public MolangExpression creation = MolangParser.ZERO;
public MolangExpression update = MolangParser.ZERO;
/* Blockbuster specific expression - local inside a particle (added by Chryfi) */
public MolangExpression particleUpdate = MolangParser.ZERO;
public BedrockComponentBase fromJson(JsonElement elem, MolangParser parser) throws MolangException
{
if (!elem.isJsonObject()) return super.fromJson(elem, parser);
JsonObject element = elem.getAsJsonObject();
if (element.has("creation_expression")) this.creation = parser.parseGlobalJson(element.get("creation_expression"));
if (element.has("per_update_expression")) this.update = parser.parseGlobalJson(element.get("per_update_expression"));
if (element.has("particle_update_expression")) this.particleUpdate = parser.parseGlobalJson(element.get("particle_update_expression"));
return super.fromJson(element, parser);
}
@Override
public JsonElement toJson()
{
JsonObject object = new JsonObject();
if (!MolangExpression.isZero(this.creation)) object.add("creation_expression", this.creation.toJson());
if (!MolangExpression.isZero(this.update)) object.add("per_update_expression", this.update.toJson());
if (!MolangExpression.isZero(this.particleUpdate)) object.add("particle_update_expression", this.particleUpdate.toJson());
return object;
}
@Override
public void apply(BedrockEmitter emitter)
{
emitter.initialValues.clear();
this.creation.get();
this.cacheInitialValues(this.creation, emitter);
if (emitter.variables != null)
{
for (Map.Entry<String, IValue> entry : emitter.variables.entrySet())
{
emitter.initialValues.put(entry.getKey(), entry.getValue().get().doubleValue());
}
}
}
@Override
public void update(BedrockEmitter emitter)
{
this.update.get();
this.cacheInitialValues(this.update, emitter);
emitter.replaceVariables();
}
private void cacheInitialValues(MolangExpression e, BedrockEmitter emitter)
{
if (e instanceof MolangMultiStatement)
{
MolangMultiStatement statement = (MolangMultiStatement) e;
for (MolangExpression expression : statement.expressions)
{
if (expression instanceof MolangAssignment)
{
this.cacheInitialValue((MolangAssignment) expression, emitter);
}
}
}
else if (e instanceof MolangAssignment)
{
this.cacheInitialValue((MolangAssignment) e, emitter);
}
}
private void cacheInitialValue(MolangAssignment assignment, BedrockEmitter emitter)
{
emitter.initialValues.put(assignment.variable.getName(), assignment.variable.get().doubleValue());
}
} | 3,946 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
URLDownloadThread.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/textures/URLDownloadThread.java | package mchorse.blockbuster.client.textures;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import javax.imageio.ImageIO;
import mchorse.mclib.utils.ReflectionUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.util.ResourceLocation;
/**
* URL download thread
*
* This bad boy downloads a picture from internet and puts it into the
* texture manager's.
*/
public class URLDownloadThread implements Runnable
{
/**
* Look, MA! I'm Google Chrome on OS X!!! xD
*/
public static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36";
private ResourceLocation url;
public URLDownloadThread(ResourceLocation url)
{
this.url = url;
}
public static InputStream downloadImage(final ResourceLocation url) throws IOException
{
URLConnection con = new URL(url.toString()).openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
InputStream stream = con.getInputStream();
String type = con.getHeaderField("Content-Type");
if (type != null && !type.startsWith("image/"))
{
return null;
}
return stream;
}
public static void addToManager(ResourceLocation url, InputStream is) throws IOException
{
BufferedImage image = ImageIO.read(is);
SimpleTexture texture = new SimpleTexture(url);
TextureUtil.uploadTextureImageAllocate(texture.getGlTextureId(), image, false, false);
TextureManager manager = Minecraft.getMinecraft().renderEngine;
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(manager);
map.put(url, texture);
}
@Override
public void run()
{
Minecraft.getMinecraft().addScheduledTask(() ->
{
try
{
InputStream stream = downloadImage(this.url);
if (stream != null)
{
addToManager(this.url, stream);
}
}
catch (IOException e)
{}
});
}
} | 2,530 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GifTexture.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/textures/GifTexture.java | package mchorse.blockbuster.client.textures;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import mchorse.mclib.utils.MathUtils;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GifTexture extends AbstractTexture
{
public static int globalTick = 0;
public static int entityTick = -1;
public static boolean tried = false;
public static Field fieldMultiTex = null;
public ResourceLocation base;
public ResourceLocation[] frames;
public int[] delays;
public int duration;
public static void bindTexture(ResourceLocation location, int ticks, float partialTicks)
{
TextureManager textures = Minecraft.getMinecraft().renderEngine;
if (location.getResourcePath().endsWith("gif"))
{
ITextureObject object = textures.getTexture(location);
if (object instanceof GifTexture)
{
GifTexture texture = (GifTexture) object;
location = texture.getFrame(ticks, partialTicks);
}
}
textures.bindTexture(location);
}
public static void updateTick()
{
globalTick += 1;
}
public GifTexture(ResourceLocation texture, int[] delays, ResourceLocation[] frames)
{
this.base = texture;
this.delays = Arrays.copyOf(delays, delays.length);
this.frames = frames;
}
public void calculateDuration()
{
this.duration = 0;
for (int delay : this.delays)
{
this.duration += delay;
}
}
@Override
public void loadTexture(IResourceManager resourceManager) throws IOException
{}
@Override
public int getGlTextureId()
{
Minecraft mc = Minecraft.getMinecraft();
TextureManager textures = mc.renderEngine;
ResourceLocation rl = this.getFrame(entityTick > -1 ? entityTick : globalTick, mc.getRenderPartialTicks());
textures.bindTexture(rl);
ITextureObject texture = textures.getTexture(rl);
this.updateMultiTex(texture);
return texture.getGlTextureId();
}
@Override
public void deleteGlTexture()
{}
public ResourceLocation getFrame(int ticks, float partialTicks)
{
int tick = (int) ((ticks + partialTicks) * 5 % this.duration);
int duration = 0;
int index = 0;
for (int delay : this.delays)
{
duration += delay;
if (tick < duration)
{
break;
}
index++;
}
index = MathUtils.clamp(index, 0, this.frames.length - 1);
return this.frames[index];
}
private void updateMultiTex(ITextureObject texture)
{
if (!tried)
{
try
{
fieldMultiTex = AbstractTexture.class.getField("multiTex");
}
catch (NoSuchFieldException | SecurityException e)
{
fieldMultiTex = null;
}
tried = true;
}
if (texture instanceof AbstractTexture && fieldMultiTex != null)
{
try
{
Object obj = fieldMultiTex.get(texture);
fieldMultiTex.set(this, obj);
}
catch (IllegalArgumentException | IllegalAccessException e)
{}
}
}
}
| 3,858 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GifProcessThread.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/textures/GifProcessThread.java | package mchorse.blockbuster.client.textures;
import java.util.HashMap;
import java.util.Map;
import at.dhyan.open_imaging.GifDecoder.GifImage;
import mchorse.blockbuster.client.RenderingHandler;
import mchorse.blockbuster.utils.mclib.GifFolder;
import mchorse.mclib.utils.ReflectionUtils;
import mchorse.mclib.utils.resources.MultiResourceLocation;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* GIF process thread
*
* This bad boy is responsible for creating an animated GIF texture
*/
@SideOnly(Side.CLIENT)
public class GifProcessThread implements Runnable
{
public static final Map<ResourceLocation, GifProcessThread> THREADS = new HashMap<ResourceLocation, GifProcessThread>();
public ResourceLocation texture;
public GifFolder gifFile;
public GifProcessThread(ResourceLocation texture, GifFolder gif)
{
this.texture = texture;
this.gifFile = gif;
}
@Override
public void run()
{
if (this.texture instanceof MultiResourceLocation)
{
return;
}
try
{
Minecraft mc = Minecraft.getMinecraft();
GifImage image = this.gifFile.gif;
int[] delays = new int[image.getFrameCount()];
ResourceLocation[] frames = new ResourceLocation[delays.length];
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(mc.renderEngine);
for (int i = 0; i < delays.length; i++)
{
delays[i] = image.getDelay(i);
frames[i] = RLUtils.create(this.texture.getResourceDomain(), this.texture.getResourcePath() + ">/frame" + i + ".png");
ITextureObject old = map.remove(frames[i]);
if (old != null)
{
if (old instanceof AbstractTexture)
{
((AbstractTexture) old).deleteGlTexture();
}
}
mc.renderEngine.loadTexture(frames[i], new GifFrameTexture(this.gifFile, i));
}
GifTexture texture = new GifTexture(this.texture, delays, frames);
ITextureObject old = map.remove(this.texture);
if (old != null)
{
if (old instanceof AbstractTexture)
{
((AbstractTexture) old).deleteGlTexture();
}
}
map.put(this.texture, texture);
texture.calculateDuration();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void create(ResourceLocation location, GifFolder gif)
{
GifProcessThread thread = new GifProcessThread(location, gif);
THREADS.put(location, thread);
thread.run();
THREADS.remove(location);
}
} | 3,171 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GifFrameTexture.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/textures/GifFrameTexture.java | package mchorse.blockbuster.client.textures;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import mchorse.blockbuster.utils.mclib.GifFolder;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.IResourceManager;
public class GifFrameTexture extends AbstractTexture
{
public GifFolder file;
public int index;
public GifFrameTexture(GifFolder file, int index)
{
this.file = file;
this.index = index;
}
@Override
public void loadTexture(IResourceManager resourceManager) throws IOException
{
this.deleteGlTexture();
if (!this.file.exists())
{
throw new FileNotFoundException(this.file.getFilePath());
}
if (!tryLoadMultiTex())
{
TextureUtil.uploadTextureImage(this.getGlTextureId(), this.file.gif.getFrame(this.index));
}
}
private boolean tryLoadMultiTex()
{
try
{
Class<?> config = Class.forName("Config");
Method isShaders = config.getMethod("isShaders");
if (!Boolean.TRUE.equals(isShaders.invoke(null)))
{
return false;
}
}
catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
return false;
}
BufferedImage frame = this.file.gif.getFrame(this.index);
int width = frame.getWidth();
int height = frame.getHeight();
int[] aint = new int[width * height * 3];
frame.getRGB(0, 0, width, height, aint, 0, width);
String path = this.file.getFilePath();
path = path.substring(0, path.length() - 4);
GifFolder normal = new GifFolder(path + "_n.gif");
GifFolder specular = new GifFolder(path + "_s.gif");
if (normal.exists())
{
frame = normal.gif.getFrame(this.index);
frame.getRGB(0, 0, width, height, aint, width * height, width);
}
else
{
Arrays.fill(aint, width * height, width * height * 2, 0xFF7F7FFF);
}
if (specular.exists())
{
frame = specular.gif.getFrame(this.index);
frame.getRGB(0, 0, width, height, aint, width * height * 2, width);
}
else
{
Arrays.fill(aint, width * height * 2, width * height * 3, 0);
}
try
{
Class<?> shadersTex = Class.forName("net.optifine.shaders.ShadersTex");
Method getMultiTexID = null;
Method setupTexture = null;
for (Method method : shadersTex.getMethods())
{
if ("getMultiTexID".equals(method.getName()))
{
getMultiTexID = method;
}
else if ("setupTexture".equals(method.getName()))
{
setupTexture = method;
}
}
if (getMultiTexID == null || setupTexture == null)
{
return false;
}
Object multiTex = getMultiTexID.invoke(null, this);
setupTexture.invoke(null, multiTex, aint, width, height, false, false);
}
catch (ClassNotFoundException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
return false;
}
return true;
}
}
| 3,783 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
MipmapTexture.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/textures/MipmapTexture.java | package mchorse.blockbuster.client.textures;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.commons.io.IOUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL14;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Mipmap texture class
*
* This class is responsible for loading or rather replacing a regular
* texture with a mipmapped version of a texture.
*/
@SideOnly(Side.CLIENT)
public class MipmapTexture extends SimpleTexture
{
/**
* Create a byte buffer from buffered image
*/
public static ByteBuffer bytesFromBuffer(BufferedImage image)
{
int w = image.getWidth();
int h = image.getHeight();
ByteBuffer buffer = GLAllocation.createDirectByteBuffer(w * h * 4);
int[] pixels = new int[w * h];
image.getRGB(0, 0, w, h, pixels, 0, w);
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
int pixel = pixels[y * w + x];
buffer.put((byte) ((pixel >> 16) & 0xFF));
buffer.put((byte) ((pixel >> 8) & 0xFF));
buffer.put((byte) (pixel & 0xFF));
buffer.put((byte) ((pixel >> 24) & 0xFF));
}
}
buffer.flip();
return buffer;
}
public MipmapTexture(ResourceLocation textureResourceLocation)
{
super(textureResourceLocation);
}
@Override
public void loadTexture(IResourceManager resourceManager) throws IOException
{
super.loadTexture(resourceManager);
IResource resource = null;
try
{
resource = resourceManager.getResource(this.textureLocation);
BufferedImage image = TextureUtil.readBufferedImage(resource.getInputStream());
int id = this.getGlTextureId();
int w = image.getWidth();
int h = image.getHeight();
GlStateManager.bindTexture(id);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MIN_LOD, 0);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LOD, 3);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 3);
GlStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0F);
GlStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_GENERATE_MIPMAP, GL11.GL_TRUE);
GlStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_LINEAR);
GlStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST_MIPMAP_LINEAR);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, w, h, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, bytesFromBuffer(image));
}
finally
{
IOUtils.closeQuietly(resource);
}
}
} | 3,415 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
RenderCustomModel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/RenderCustomModel.java | package mchorse.blockbuster.client.render;
import java.util.List;
import java.util.Map;
import javax.vecmath.Matrix4d;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector4f;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import mchorse.blockbuster.common.OrientedBB;
import mchorse.blockbuster_pack.morphs.CustomMorph;
import mchorse.blockbuster_pack.morphs.SnowstormMorph;
import mchorse.mclib.utils.MatrixUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderCustomModel extends RenderLivingBase<EntityLivingBase>
{
/**
* Last bind texture
*/
public static ResourceLocation lastTexture;
/**
* Currently used morph
*/
public CustomMorph current;
private int captured;
private boolean capturedByMe;
public static void bindLastTexture(ResourceLocation location)
{
lastTexture = location;
bindLastTexture();
}
public static void bindLastTexture()
{
if (lastTexture != null)
{
Minecraft.getMinecraft().renderEngine.bindTexture(lastTexture);
}
}
public RenderCustomModel(RenderManager renderManagerIn, ModelBase modelBaseIn, float shadowSizeIn)
{
super(renderManagerIn, null, shadowSizeIn);
}
/**
* Get default texture for entity
*/
@Override
protected ResourceLocation getEntityTexture(EntityLivingBase entity)
{
return this.mainModel == null ? null : ((ModelCustom) this.mainModel).model.defaultTexture;
}
protected boolean bindEntityTexture(EntityLivingBase entity)
{
if (this.mainModel != null && ((ModelCustom) this.mainModel).model.providesMtl)
{
ResourceLocation texture = this.getEntityTexture(entity);
if (texture == null)
{
return true;
}
}
return super.bindEntityTexture(entity);
}
/**
* Override method in order to save the last texture. Used by OBJ
* renderer with materials to bind texture back
*/
@Override
public void bindTexture(ResourceLocation location)
{
lastTexture = location;
super.bindTexture(location);
}
/**
* Render morph's name only if the player is pointed at the entity
*/
@Override
protected boolean canRenderName(EntityLivingBase entity)
{
return super.canRenderName(entity) && entity.hasCustomName() && entity == this.renderManager.pointedEntity;
}
@Override
public void doRender(EntityLivingBase entity, double x, double y, double z, float entityYaw, float partialTicks)
{
this.setupModel(entity, partialTicks);
if (this.mainModel != null)
{
super.doRender(entity, x, y, z, entityYaw, partialTicks);
}
if (this.captured > 0)
{
this.captured --;
if (this.captured == 0 && this.capturedByMe)
{
MatrixUtils.releaseMatrix();
this.capturedByMe = false;
}
}
}
@Override
protected void renderLivingAt(EntityLivingBase entityLivingBaseIn, double x, double y, double z)
{
super.renderLivingAt(entityLivingBaseIn, x, y, z);
if (this.captured == 0)
{
this.capturedByMe = MatrixUtils.captureMatrix();
}
this.captured ++;
}
/**
* Setup the model for player instance.
*
* This method is responsible for picking the right model and pose based
* on player properties.
*/
public void setupModel(EntityLivingBase entity, float partialTicks)
{
Map<String, ModelCustom> models = ModelCustom.MODELS;
ModelCustom model = null;
ModelPose pose = null;
if (this.current != null)
{
model = models.get(this.current.getKey());
pose = this.current.getPose(entity, partialTicks);
}
if (model != null)
{
if (pose == null)
{
pose = model.model.getPose("standing");
}
model.materials = this.current.materials;
model.shapes = this.current.getShapesForRendering(partialTicks);
model.pose = pose;
model.current = this.current;
this.mainModel = model;
}
}
/**
* Make player a little bit smaller (so he looked like steve, and not like an
* overgrown rodent).
*/
@Override
protected void preRenderCallback(EntityLivingBase entity, float partialTickTime)
{
Model model = ((ModelCustom) this.mainModel).model;
float scale = this.current == null ? 1.0F : this.current.scale;
GlStateManager.scale(model.scale[0] * scale, model.scale[1] * scale, model.scale[2] * scale);
}
/**
* Taken from RenderPlayer
*
* This code is primarily changes the angle of the player while it's flying
* an elytra. You know?
*/
@Override
protected void applyRotations(EntityLivingBase entity, float pitch, float yaw, float partialTicks)
{
if (entity.isEntityAlive() && entity.isPlayerSleeping())
{
/* Nap time! */
GlStateManager.rotate(((EntityPlayer) entity).getBedOrientationInDegrees(), 0.0F, 1.0F, 0.0F);
GlStateManager.rotate(this.getDeathMaxRotation(entity), 0.0F, 0.0F, 1.0F);
GlStateManager.rotate(270.0F, 0.0F, 1.0F, 0.0F);
}
else if (entity.isElytraFlying())
{
/* Elytra rotation */
super.applyRotations(entity, pitch, yaw, partialTicks);
float f = entity.getTicksElytraFlying() + partialTicks;
float f1 = MathHelper.clamp(f * f / 100.0F, 0.0F, 1.0F);
Vec3d vec3d = entity.getLook(partialTicks);
double d0 = entity.motionX * entity.motionX + entity.motionZ * entity.motionZ;
double d1 = vec3d.x * vec3d.x + vec3d.z * vec3d.z;
GlStateManager.rotate(f1 * (-90.0F - entity.rotationPitch), 1.0F, 0.0F, 0.0F);
if (d0 > 0.0D && d1 > 0.0D)
{
double d2 = (entity.motionX * vec3d.x + entity.motionZ * vec3d.z) / (Math.sqrt(d0) * Math.sqrt(d1));
double d3 = entity.motionX * vec3d.z - entity.motionZ * vec3d.x;
GlStateManager.rotate((float) (Math.signum(d3) * Math.acos(d2)) * 180.0F / (float) Math.PI, 0.0F, 1.0F, 0.0F);
}
}
else
{
super.applyRotations(entity, pitch, yaw, partialTicks);
}
}
/**
* Render right hand
*/
public void renderRightArm(EntityPlayer player)
{
ResourceLocation texture = this.getEntityTexture(player);
if (texture != null)
{
this.bindTexture(texture);
}
this.mainModel.swingProgress = 0.0F;
this.mainModel.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F, player);
GlStateManager.color(1.0F, 1.0F, 1.0F);
GlStateManager.enableBlend();
for (ModelCustomRenderer arm : ((ModelCustom) this.mainModel).right)
{
arm.rotateAngleX = 0;
arm.rotationPointX = -6;
arm.rotationPointY = 13.8F - (arm.limb.size[1] > 8 ? arm.limb.size[1] : arm.limb.size[1] + 2);
arm.rotationPointZ = 0;
arm.render(0.0625F);
}
GlStateManager.disableBlend();
}
/**
* Render left hand
*/
public void renderLeftArm(EntityPlayer player)
{
ResourceLocation texture = this.getEntityTexture(player);
if (texture != null)
{
this.bindTexture(texture);
}
this.mainModel.swingProgress = 0.0F;
this.mainModel.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F, player);
GlStateManager.color(1.0F, 1.0F, 1.0F);
GlStateManager.enableBlend();
for (ModelCustomRenderer arm : ((ModelCustom) this.mainModel).left)
{
arm.rotateAngleX = 0;
arm.rotationPointX = 6;
arm.rotationPointY = 13.8F - (arm.limb.size[1] > 8 ? arm.limb.size[1] : arm.limb.size[1] + 2F);
arm.rotationPointZ = 0;
arm.render(0.0625F);
}
GlStateManager.disableBlend();
}
} | 9,074 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GunMiscRender.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/GunMiscRender.java | package mchorse.blockbuster.client.render;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.KeyboardHandler;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.common.item.ItemGun;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.guns.PacketZoomCommand;
import mchorse.blockbuster.utils.NBTUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.util.vector.Vector3f;
/**
* \* User: Evanechecssss
* \* https://bio.link/evanechecssss
* \* Data: 17.11.2021
* \* Description:
* \
*/
@SideOnly(Side.CLIENT)
public class GunMiscRender
{
public static float ZOOM_TIME;
public static float UN_ZOOM_TIME;
public static boolean onZoom = true;
private boolean hasChangedSensitivity = false;
private boolean hasChangedFov = false;
private float lastMouseSensitivity;
private float lastFov;
public Vector3f translate = new Vector3f();
public Vector3f scale = new Vector3f(1F, 1F, 1F);
public Vector3f rotate = new Vector3f();
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onTick(TickEvent.RenderTickEvent event)
{
if (Minecraft.getMinecraft().player != null && event.phase.equals(TickEvent.Phase.END))
{
EntityPlayer player = Minecraft.getMinecraft().player;
ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND);
GunProps props = NBTUtils.getGunProps(heldItem);
if (heldItem.getItem().equals(Blockbuster.gunItem))
{
this.handleZoom(event.renderTickTime);
}
if (ZOOM_TIME == 0)
{
if (hasChangedFov)
{
hasChangedFov = false;
Minecraft.getMinecraft().gameSettings.fovSetting = lastFov;
}
else
{
lastFov = Minecraft.getMinecraft().gameSettings.fovSetting;
}
Minecraft.getMinecraft().renderGlobal.setDisplayListEntitiesDirty();
if (hasChangedSensitivity)
{
hasChangedSensitivity = false;
Minecraft.getMinecraft().gameSettings.mouseSensitivity = lastMouseSensitivity;
}
else
{
lastMouseSensitivity = Minecraft.getMinecraft().gameSettings.mouseSensitivity;
}
}
else if (ZOOM_TIME != 0)
{
if (heldItem.getItem().equals(Blockbuster.gunItem) && KeyboardHandler.zoom.isKeyDown())
{
hasChangedSensitivity = true;
hasChangedFov = true;
if (props != null)
{
Minecraft.getMinecraft().gameSettings.mouseSensitivity = lastMouseSensitivity * props.mouseZoom - 0.3f;
Minecraft.getMinecraft().gameSettings.fovSetting = lastFov - lastFov * ZOOM_TIME * props.zoomFactor;
Minecraft.getMinecraft().renderGlobal.setDisplayListEntitiesDirty();
}
}
else
{
hasChangedSensitivity = true;
hasChangedFov = true;
Minecraft.getMinecraft().gameSettings.mouseSensitivity = lastMouseSensitivity;
Minecraft.getMinecraft().gameSettings.fovSetting = lastFov;
}
}
}
}
private void handleZoom(float partialTick)
{
boolean zoomed = onZoom;
if (KeyboardHandler.zoom.isKeyDown())
{
onZoom = true;
ZOOM_TIME = Math.min(ZOOM_TIME + partialTick * 0.1F, 1);
UN_ZOOM_TIME = Math.max(UN_ZOOM_TIME - partialTick * 0.2F, 0);
if (!zoomed)
{
Dispatcher.sendToServer(new PacketZoomCommand(Minecraft.getMinecraft().player.getEntityId(), true));
}
}
else
{
onZoom = false;
ZOOM_TIME = Math.max(ZOOM_TIME - partialTick * 0.1F, 0);
UN_ZOOM_TIME = Math.min(UN_ZOOM_TIME + partialTick * 0.2F, 1);
if (zoomed)
{
Dispatcher.sendToServer(new PacketZoomCommand(Minecraft.getMinecraft().player.getEntityId(), false));
}
}
}
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void renderGameOverlay(RenderGameOverlayEvent event)
{
if (event.getType() == RenderGameOverlayEvent.ElementType.CROSSHAIRS)
{
Minecraft mc = Minecraft.getMinecraft();
ItemStack gun = mc.player.getHeldItemMainhand();
if (gun.getItem() instanceof ItemGun)
{
GunProps props = NBTUtils.getGunProps(gun);
if (props == null)
{
return;
}
if ((props.hideCrosshairOnZoom && KeyboardHandler.zoom.isKeyDown()) || !props.currentCrosshair.isEmpty())
{
event.setCanceled(true);
}
}
}
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onHUDRender(RenderGameOverlayEvent.Post event)
{
ScaledResolution resolution = event.getResolution();
if (event.getType() == RenderGameOverlayEvent.ElementType.ALL)
{
EntityPlayer player = Minecraft.getMinecraft().player;
if (player.getHeldItemMainhand().getItem() instanceof ItemGun)
{
GunProps props = NBTUtils.getGunProps(player.getHeldItemMainhand());
if (props != null && props.crosshairMorph != null && !(KeyboardHandler.zoom.isKeyDown() && props.hideCrosshairOnZoom))
{
render(props.currentCrosshair.get(), resolution.getScaledWidth(), resolution.getScaledHeight());
}
}
}
}
public void render(AbstractMorph morph, int width, int height)
{
if (morph == null)
{
return;
}
Minecraft mc = Minecraft.getMinecraft();
GlStateManager.pushMatrix();
GlStateManager.translate(0.5F, 0, 0.5F);
enableGLStates();
morph.renderOnScreen(mc.player, (width / 2) + (int) morph.cachedTranslation.x, (height / 2) + (int) morph.cachedTranslation.y, 15, 1f);
GlStateManager.popMatrix();
}
private void enableGLStates()
{
RenderHelper.enableStandardItemLighting();
GlStateManager.enableBlend();
GlStateManager.enableAlpha();
GlStateManager.enableRescaleNormal();
GlStateManager.enableDepth();
GlStateManager.disableCull();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
}
} | 7,740 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IRenderLast.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/IRenderLast.java | package mchorse.blockbuster.client.render;
import javax.vecmath.Vector3d;
public interface IRenderLast
{
/**
* @return the position used to depth sort
*/
public Vector3d getRenderLastPos();
}
| 212 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
RenderExpirableDummy.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/RenderExpirableDummy.java | package mchorse.blockbuster.client.render;
import mchorse.blockbuster.common.entity.ExpirableDummyEntity;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import javax.annotation.Nullable;
public class RenderExpirableDummy extends RenderLivingBase<ExpirableDummyEntity> {
public RenderExpirableDummy(RenderManager renderManagerIn, ModelBase modelBaseIn, float shadowSizeIn) {
super(renderManagerIn, modelBaseIn, shadowSizeIn);
}
@Override
public void doRenderShadowAndFire(Entity entityIn, double x, double y, double z, float yaw, float partialTicks) {}
@Override
public boolean shouldRender(ExpirableDummyEntity livingEntity, ICamera camera, double camX, double camY, double camZ)
{
return false;
}
@Override
public void doRender(ExpirableDummyEntity entity, double x, double y, double z, float entityYaw, float partialTicks) { }
@Nullable
@Override
protected ResourceLocation getEntityTexture(ExpirableDummyEntity entity) {
return null;
}
public static class FactoryExpirableDummy implements IRenderFactory<ExpirableDummyEntity>
{
@Override
public RenderExpirableDummy createRenderFor(RenderManager manager)
{
return new RenderExpirableDummy(manager, null, 0);
}
}
}
| 1,626 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
RenderActor.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/RenderActor.java | package mchorse.blockbuster.client.render;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.client.RenderingHandler;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster_pack.morphs.CustomMorph;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
/**
* Render actor class
*
* Render actor entities with custom swaggalicious models ?8|
*/
public class RenderActor extends RenderLiving<EntityActor>
{
/**
* Default texture of the renderer
*/
private static final ResourceLocation defaultTexture = new ResourceLocation(Blockbuster.MOD_ID, "textures/entity/actor.png");
/**
* Initiate render actor
*/
public RenderActor(RenderManager manager, float shadow)
{
super(manager, null, shadow);
}
/**
* Use skin from resource pack or default one (if skin is empty or just
* wasn't found by actor pack)
*/
@Override
protected ResourceLocation getEntityTexture(EntityActor entity)
{
return defaultTexture;
}
@Override
public boolean shouldRender(EntityActor livingEntity, ICamera camera, double camX, double camY, double camZ)
{
if (livingEntity.renderLast && RenderingHandler.addRenderLast(livingEntity))
{
return false;
}
if (Blockbuster.actorAlwaysRender.get())
{
return true;
}
return super.shouldRender(livingEntity, camera, camX, camY, camZ);
}
@Override
public void doRender(EntityActor entity, double x, double y, double z, float entityYaw, float partialTicks)
{
this.shadowOpaque = 0;
if (entity.invisible)
{
this.renderPlayerRecordingName(entity, x, y, z);
return;
}
AbstractMorph morph = entity.getMorph();
if (morph != null)
{
this.shadowOpaque = 1.0F;
float shadow = 0.5F;
if (morph instanceof CustomMorph)
{
CustomMorph custom = (CustomMorph) morph;
if (custom.model != null)
{
shadow = custom.getWidth(entity) * custom.model.scale[0];
}
}
this.shadowSize = shadow;
morph.render(entity, x, y, z, entityYaw, partialTicks);
}
this.renderLeash(entity, x, y, z, entityYaw, partialTicks);
this.renderPlayerRecordingName(entity, x, y, z);
if (entity.playback != null && entity.playback.record != null)
{
RenderingHandler.recordsToRender.add(entity.playback.record);
}
}
/**
* Renders player recording name
*/
private void renderPlayerRecordingName(EntityActor entity, double x, double y, double z)
{
if (!Minecraft.getMinecraft().gameSettings.showDebugInfo)
{
return;
}
final double maxDistance = 64;
double d0 = entity.getDistanceSq(this.renderManager.renderViewEntity);
if (d0 <= (maxDistance * maxDistance) && entity.playback != null && entity.playback.record != null)
{
float viewerYaw = this.renderManager.playerViewY;
float viewerPitch = this.renderManager.playerViewX;
boolean isThirdPersonFrontal = this.renderManager.options.thirdPersonView == 2;
float f2 = entity.height / 2;
String str = entity.playback.record.filename;
FontRenderer fontRendererIn = this.getFontRendererFromRenderManager();
int verticalShift = -fontRendererIn.FONT_HEIGHT / 2;
y += f2;
int shader = GL11.glGetInteger(GL20.GL_CURRENT_PROGRAM);
if (shader != 0)
{
OpenGlHelper.glUseProgram(0);
}
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
GlStateManager.glNormal3f(0.0F, 1.0F, 0.0F);
GlStateManager.rotate(-viewerYaw, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate((float)(isThirdPersonFrontal ? -1 : 1) * viewerPitch, 1.0F, 0.0F, 0.0F);
GlStateManager.scale(-0.025F, -0.025F, 0.025F);
GlStateManager.disableLighting();
GlStateManager.disableDepth();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
int i = fontRendererIn.getStringWidth(str) / 2;
GlStateManager.disableTexture2D();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
vertexbuffer.begin(7, DefaultVertexFormats.POSITION_COLOR);
vertexbuffer.pos((double)(-i - 1), (double)(-1 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
vertexbuffer.pos((double)(-i - 1), (double)(8 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
vertexbuffer.pos((double)(i + 1), (double)(8 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
vertexbuffer.pos((double)(i + 1), (double)(-1 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
tessellator.draw();
GlStateManager.enableTexture2D();
fontRendererIn.drawString(str, -fontRendererIn.getStringWidth(str) / 2, verticalShift, -1);
GlStateManager.enableDepth();
GlStateManager.enableLighting();
GlStateManager.disableBlend();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.popMatrix();
if (shader != 0)
{
OpenGlHelper.glUseProgram(shader);
}
}
}
/**
* Renderer factory
*
* Some interface provided by Minecraft Forge that will pass a RenderManager
* instance into the method for easier Renders initiation.
*/
public static class FactoryActor implements IRenderFactory<EntityActor>
{
@Override
public RenderActor createRenderFor(RenderManager manager)
{
return new RenderActor(manager, 0.5F);
}
}
} | 6,999 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
RenderGunProjectile.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/RenderGunProjectile.java | package mchorse.blockbuster.client.render;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.common.entity.EntityGunProjectile;
import mchorse.mclib.utils.Interpolations;
import mchorse.mclib.utils.MatrixUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.IRenderFactory;
/**
* Gun projectile renderer
*
* This bad boy is responsible for rendering the projectile shot from
* the gun.
*/
public class RenderGunProjectile extends Render<EntityGunProjectile>
{
protected RenderGunProjectile(RenderManager renderManager)
{
super(renderManager);
}
@Override
public boolean shouldRender(EntityGunProjectile livingEntity, ICamera camera, double camX, double camY, double camZ)
{
if (Blockbuster.actorAlwaysRender.get())
{
return true;
}
return super.shouldRender(livingEntity, camera, camX, camY, camZ);
}
@Override
protected ResourceLocation getEntityTexture(EntityGunProjectile entity)
{
return null;
}
@Override
public void doRender(EntityGunProjectile entity, double x, double y, double z, float entityYaw, float partialTicks)
{
AbstractMorph morph = entity.morph.get();
if (entity.props != null && morph != null)
{
int length = entity.props.lifeSpan;
float timer = entity.ticksExisted + partialTicks;
float scale = Interpolations.envelope(timer > length ? length : timer, 0, entity.props.fadeIn, length - entity.props.fadeOut, length);
if (entity.vanish && entity.props.vanishDelay > 0)
{
scale = Interpolations.envelope(entity.vanishDelay - partialTicks, 0, entity.props.fadeOut, entity.props.vanishDelay, entity.props.vanishDelay);
}
/* A small scale factor to avoid Z fighting */
scale += (entity.getEntityId() % 100) / 10000F;
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
boolean captured = MatrixUtils.captureMatrix();
GlStateManager.scale(scale, scale, scale);
if (entity.props.yaw) GlStateManager.rotate(entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks, 0.0F, 1.0F, 0.0F);
if (entity.props.pitch) GlStateManager.rotate(-(entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * partialTicks) + 90, 1.0F, 0.0F, 0.0F);
entity.props.projectileTransform.transform();
entity.props.createEntity();
morph.render(entity.props.getEntity(entity), 0, 0, 0, 0, partialTicks);
if (captured)
{
MatrixUtils.releaseMatrix();
}
GlStateManager.popMatrix();
}
}
public static class FactoryGunProjectile implements IRenderFactory<EntityGunProjectile>
{
@Override
public Render<? super EntityGunProjectile> createRenderFor(RenderManager manager)
{
return new RenderGunProjectile(manager);
}
}
} | 3,403 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
LayerHeldItem.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/layer/LayerHeldItem.java | package mchorse.blockbuster.client.render.layer;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.layers.LayerRenderer;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHandSide;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* This is patched LayerHeldItem layer class. This class is responsible for
* rendering items in designated limbs in custom actor model. Lots of fun
* stuff going on here.
*/
@SideOnly(Side.CLIENT)
public class LayerHeldItem implements LayerRenderer<EntityLivingBase>
{
protected final RenderLivingBase<?> livingEntityRenderer;
public LayerHeldItem(RenderLivingBase<?> livingEntityRendererIn)
{
this.livingEntityRenderer = livingEntityRendererIn;
}
@Override
public void doRenderLayer(EntityLivingBase entity, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch, float scale)
{
ItemStack itemstack1 = entity.getHeldItemMainhand();
ItemStack itemstack = entity.getHeldItemOffhand();
if (!itemstack.isEmpty() || !itemstack1.isEmpty())
{
HeldModel model = new HeldModel(((ModelCustom) this.livingEntityRenderer.getMainModel()));
model.limbSwing = limbSwing;
model.limbSwingAmount = limbSwingAmount;
model.ageInTicks = ageInTicks;
model.netHeadYaw = netHeadYaw;
model.headPitch = headPitch;
model.scale = scale;
renderHeldItem(entity, itemstack1, model, ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND, EnumHandSide.RIGHT);
renderHeldItem(entity, itemstack, model, ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND, EnumHandSide.LEFT);
model.model.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entity);
}
}
/**
* Render item in every arm.
*
* <p>Items could be rendered to several limbs.</p>
*/
public static void renderHeldItem(EntityLivingBase entity, ItemStack item, HeldModel model, ItemCameraTransforms.TransformType transform, EnumHandSide handSide)
{
if (!item.isEmpty())
{
for (ModelCustomRenderer arm : model.model.getRenderForArm(handSide))
{
boolean flag = handSide == EnumHandSide.LEFT;
model.setup(entity);
GlStateManager.pushMatrix();
applyTransform(arm);
Minecraft.getMinecraft().getItemRenderer().renderItemSide(entity, item, transform, flag);
GlStateManager.popMatrix();
}
}
}
/**
* Render item in every arm.
* <p>
* Items could be rendered to several limbs.
*/
public static void renderHeldItem(EntityLivingBase entity, ItemStack item, ModelCustom model, ItemCameraTransforms.TransformType transform, EnumHandSide handSide)
{
if (item != null)
{
for (ModelCustomRenderer arm : model.getRenderForArm(handSide))
{
boolean flag = handSide == EnumHandSide.LEFT;
GlStateManager.pushMatrix();
applyTransform(arm);
Minecraft.getMinecraft().getItemRenderer().renderItemSide(entity, item, transform, flag);
GlStateManager.popMatrix();
}
}
}
private static void applyTransform(ModelCustomRenderer arm)
{
float x = (arm.limb.size[0] * (0.5F - arm.limb.anchor[0])) * 0.0625F;
float y = arm.limb.size[1] * (arm.limb.size[1] * (1 - arm.limb.anchor[1]) / arm.limb.size[1]) * -0.0625F;
float z = (arm.limb.size[2] * (arm.limb.anchor[2])) * 0.0625F;
if (arm.limb.size[0] > arm.limb.size[1])
{
x = arm.limb.size[0] * (10.0F / 12.0F) * 0.0625F;
}
arm.postRender(0.0625F);
GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F);
GlStateManager.translate(x, z, y);
if (arm.limb.size[0] > arm.limb.size[1])
{
GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F);
}
GlStateManager.scale(arm.limb.itemScale, arm.limb.itemScale, arm.limb.itemScale);
}
/**
* Don't really understand how this method is going to affect the rendering
* of this layer.
*/
@Override
public boolean shouldCombineTextures()
{
return false;
}
/**
* Held model class
* <p>
* This class is responsible for storing the data related to rendering of
* some stuff in the layer class. This is needed to store the rotation and
* angles during that stage, because recursive model block item stack
* rendering messing up the angles, this class used to restore the original
* state.
*/
public static class HeldModel
{
public float limbSwing;
public float limbSwingAmount;
public float ageInTicks;
public float netHeadYaw;
public float headPitch;
public float scale;
public ModelCustom model;
public ModelPose pose;
public HeldModel(ModelCustom model)
{
this.model = model;
this.pose = model.pose;
}
public void setup(EntityLivingBase entity)
{
this.model.pose = this.pose;
this.model.setRotationAngles(this.limbSwing, this.limbSwingAmount, this.ageInTicks, this.netHeadYaw, this.headPitch, this.scale, entity);
}
}
} | 6,051 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityModelItemStackRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/tileentity/TileEntityModelItemStackRenderer.java | package mchorse.blockbuster.client.render.tileentity;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.mclib.utils.MatrixUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.vecmath.Matrix4f;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Model block's TEISR
*
* This class is responsible for rendering model blocks in inventory
*/
@SideOnly(Side.CLIENT)
public class TileEntityModelItemStackRenderer extends TileEntityItemStackRenderer
{
/**
* Default tile entity model
*/
public TileEntityModel def;
/**
* A cache of model TEs
*/
public static final Map<NBTTagCompound, TEModel> models = new HashMap<NBTTagCompound, TEModel>();
private static boolean isRendering;
public static boolean isRendering()
{
return isRendering;
}
@Override
public void renderByItem(ItemStack stack, float partialTicks)
{
/* Thank you Mojang, very cool! */
partialTicks = Minecraft.getMinecraft().getRenderPartialTicks();
if (this.def == null)
{
this.def = new TileEntityModel();
}
NBTTagCompound tag = stack.getTagCompound();
if (tag != null)
{
TEModel model = models.get(tag);
if (model == null)
{
TileEntityModel te = new TileEntityModel();
te.readFromNBT(tag.getCompoundTag("BlockEntityTag"));
model = new TEModel(te);
models.put(tag, model);
}
/*
* timer in ticks when to remove items that are not rendered anymore
* 5 should be enough to ensure that even with very low fps the model doesn't get removed unnecessarily
*/
model.timer = 5;
this.renderModel(model.model, partialTicks);
return;
}
this.renderModel(this.def, partialTicks);
}
public void renderModel(TileEntityModel model, float partialTicks)
{
isRendering = true;
ClientProxy.modelRenderer.render(model, 0, 0, 0, partialTicks, 0, 0);
Minecraft mc = Minecraft.getMinecraft();
TextureManager manager = mc.getTextureManager();
manager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
mc.getTextureMapBlocks().setBlurMipmapDirect(false, true);
mc.getTextureMapBlocks().setBlurMipmap(false, false);
isRendering = false;
}
/**
* {@link TileEntityModel} wrapper class
*
* This class allows to hold timer for unloading purpose (so objects
* won't get stuck in the map forever, which might cause memory
* leak)
*/
public static class TEModel
{
public int timer = 20;
public TileEntityModel model;
public TEModel(TileEntityModel model)
{
this.model = model;
}
}
} | 3,361 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityModelRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/tileentity/TileEntityModelRenderer.java | package mchorse.blockbuster.client.render.tileentity;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.client.gui.dashboard.panels.model_block.GuiModelBlockPanel;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.client.gui.framework.elements.input.GuiTransformations;
import mchorse.mclib.utils.MatrixUtils.RotationOrder;
import mchorse.blockbuster.common.tileentity.TileEntityModelSettings;
import mchorse.mclib.client.Draw;
import mchorse.mclib.utils.MatrixUtils;
import mchorse.mclib.utils.RenderingUtils;
import mchorse.metamorph.api.EntityUtils;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.bodypart.GuiBodyPartEditor;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import javax.vecmath.Vector3d;
import java.util.List;
/**
* Model tile entity renderer
*
* This class is responsible for rendering a model based on given tile
* entity data.
*/
public class TileEntityModelRenderer extends TileEntitySpecialRenderer<TileEntityModel>
{
/**
* Entity shadow rendering
*/
public RenderShadow renderer;
@Override
public void render(TileEntityModel te, double x, double y, double z, float partialTicks, int destroyStage, float alpha)
{
Minecraft mc = Minecraft.getMinecraft();
TileEntityModelSettings teSettings = te.getSettings();
if (!te.morph.isEmpty() && (!Blockbuster.modelBlockDisableRendering.get() || teSettings.isRenderAlways()) && teSettings.isEnabled())
{
AbstractMorph morph = te.morph.get();
if (this.renderer == null)
{
this.renderer = new RenderShadow(mc.getRenderManager());
}
if (te.entity == null)
{
te.createEntity(mc.world);
}
if (te.entity == null)
{
return;
}
EntityLivingBase entity = te.entity;
if (EntityUtils.getMorph(entity) != null)
{
morph = EntityUtils.getMorph(entity);
}
/* Apply entity rotations */
BlockPos pos = te.getPos();
entity.setPositionAndRotation(pos.getX() + 0.5F + teSettings.getX(), pos.getY() + teSettings.getY(), pos.getZ() + 0.5F + teSettings.getZ(), 0, 0);
entity.setLocationAndAngles(pos.getX() + 0.5F + teSettings.getX(), pos.getY() + teSettings.getY(), pos.getZ() + 0.5F + teSettings.getZ(), 0, 0);
entity.rotationYawHead = entity.prevRotationYawHead = teSettings.getRotateYawHead();
entity.rotationYaw = entity.prevRotationYaw = 0;
entity.rotationPitch = entity.prevRotationPitch = teSettings.getRotatePitch();
entity.renderYawOffset = entity.prevRenderYawOffset = teSettings.getRotateBody();
entity.setVelocity(0, 0, 0);
float xx = (float) x + 0.5F + teSettings.getX();
float yy = (float) y + teSettings.getY();
float zz = (float) z + 0.5F + teSettings.getZ();
/* Apply transformations */
GlStateManager.pushMatrix();
GlStateManager.translate(xx, yy, zz);
boolean wasSet = MatrixUtils.captureMatrix();
this.transform(te);
MorphUtils.render(morph, entity, 0, 0, 0, 0, partialTicks);
this.drawAxis(te);
GlStateManager.popMatrix();
if (teSettings.isShadow())
{
this.renderer.setShadowSize(morph.getWidth(entity) * 0.8F);
this.renderer.doRenderShadowAndFire(te.entity, xx, yy, zz, 0, partialTicks);
}
if (wasSet) MatrixUtils.releaseMatrix();
}
/* Debug render (so people could find the block, lmao) */
if (mc.gameSettings.showDebugInfo && (!mc.gameSettings.hideGUI || Blockbuster.modelBlockRenderDebuginf1.get()))
{
int shader = GL11.glGetInteger(GL20.GL_CURRENT_PROGRAM);
if (shader != 0)
{
OpenGlHelper.glUseProgram(0);
}
GlStateManager.disableTexture2D();
GlStateManager.disableDepth();
GlStateManager.disableLighting();
GlStateManager.enableBlend();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
float r = teSettings.isEnabled() ? 0 : 1;
float g = teSettings.isEnabled() ? 0.5F : 0.85F;
float b = teSettings.isEnabled() ? 1 : 0;
if (!te.morph.isEmpty() && te.morph.get().errorRendering)
{
r = 1;
g = b = 0;
}
Draw.cube(buffer, x + 0.25F, y + 0.25F, z + 0.25F, x + 0.75F, y + 0.75F, z + 0.75F, r, g, b, 0.35F);
Draw.cube(buffer, x + 0.45F + teSettings.getX(), y + teSettings.getY(), z + 0.45F + teSettings.getZ(), x + 0.55F + teSettings.getX(), y + 0.1F + teSettings.getY(), z + 0.55F + teSettings.getZ(), 1, 1, 1, 0.85F);
double distance = MathHelper.sqrt(Vec3d.ZERO.squareDistanceTo(teSettings.getX(), teSettings.getY(), teSettings.getZ()));
if (distance > 0.1)
{
Draw.cube(buffer, x + 0.45F, y, z + 0.45F, x + 0.55F, y + 0.1F, z + 0.55F, 1, 1, 1, 0.85F);
tessellator.draw();
double horizontalDistance = MathHelper.sqrt(teSettings.getX() * teSettings.getX() + teSettings.getZ() * teSettings.getZ());
double yaw = 180 - MathHelper.atan2(teSettings.getZ(), teSettings.getX()) * 180 / Math.PI + 90;
double pitch = MathHelper.atan2(teSettings.getY(), horizontalDistance) * 180 / Math.PI;
GL11.glPushMatrix();
GL11.glTranslated(x + 0.5, y + 0.05F, z + 0.5);
GL11.glRotated(yaw, 0.0F, 1.0F, 0.0F);
GL11.glRotated(pitch, 1.0F, 0.0F, 0.0F);
Draw.cube(-0.025F, -0.025F, 0, 0.025F, 0.025F, -distance, 0, 0, 0, 0.5F);
GL11.glPopMatrix();
}
else
{
tessellator.draw();
}
if (teSettings.getLightValue() != 0)
{
FontRenderer font = Minecraft.getMinecraft().fontRenderer;
String text = I18n.format("blockbuster.light", teSettings.getLightValue());
RenderManager manager = mc.getRenderManager();
boolean isInventory = false;
float yaw = (isInventory) ? 180F : manager.playerViewY;
float pitch = (isInventory) ? 0F : manager.playerViewX;
EntityRenderer.drawNameplate(this.getFontRenderer(), text, (float) (x + 0.5F), (float) (y + 0.5F) + font.FONT_HEIGHT / 48.0F + 0.05F, (float) (z + 0.5F), 0, yaw, pitch, mc.gameSettings.thirdPersonView == 2, false);
}
GlStateManager.disableBlend();
GlStateManager.enableLighting();
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
if (shader != 0)
{
OpenGlHelper.glUseProgram(shader);
}
}
}
private void drawAxis(TileEntityModel te)
{
List<GuiModelBlockPanel> childList = GuiBase.getCurrentChildren(GuiModelBlockPanel.class);
if (childList == null) return;
GuiModelBlockPanel modelBlockPanel = childList.get(0);
if (modelBlockPanel != null && modelBlockPanel.isOpened() && modelBlockPanel.isSelected(te))
{
GlStateManager.pushMatrix();
GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GlStateManager.disableTexture2D();
GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);
GlStateManager.disableTexture2D();
GlStateManager.disableDepth();
GlStateManager.disableLighting();
Draw.point(0, 0, 0);
if (GuiTransformations.GuiStaticTransformOrientation.getOrientation() == GuiTransformations.TransformOrientation.GLOBAL)
{
TileEntityModelSettings teSettings = te.getSettings();
Vector3d rotation = new Vector3d(Math.toRadians(teSettings.getRx()), Math.toRadians(teSettings.getRy()), Math.toRadians(teSettings.getRz()));
Vector3d scale = new Vector3d(teSettings.getSx(), teSettings.getSy(), teSettings.getSz());
RenderingUtils.glRevertRotationScale(rotation, scale, teSettings.getOrder());
}
Draw.axis(0.25F);
GlStateManager.enableLighting();
GlStateManager.enableDepth();
GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GlStateManager.enableTexture2D();
GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);
GlStateManager.enableTexture2D();
GlStateManager.popMatrix();
}
}
@Override
public boolean isGlobalRenderer(TileEntityModel te)
{
return te.getSettings().isGlobal();
}
public void transform(TileEntityModel te)
{
TileEntityModelSettings teSettings = te.getSettings();
if (teSettings.getOrder() == RotationOrder.ZYX)
{
GlStateManager.rotate(teSettings.getRx(), 1, 0, 0);
GlStateManager.rotate(teSettings.getRy(), 0, 1, 0);
GlStateManager.rotate(teSettings.getRz(), 0, 0, 1);
}
else
{
GlStateManager.rotate(teSettings.getRz(), 0, 0, 1);
GlStateManager.rotate(teSettings.getRy(), 0, 1, 0);
GlStateManager.rotate(teSettings.getRx(), 1, 0, 0);
}
/* the uniform rendering is needed for backwards compatibility
* with model blocks that have only sx set */
if (teSettings.isUniform())
{
GlStateManager.scale(teSettings.getSx(), teSettings.getSx(), teSettings.getSx());
}
else
{
GlStateManager.scale(teSettings.getSx(), teSettings.getSy(), teSettings.getSz());
}
}
/**
* Used for rendering entity shadow
*/
public static class RenderShadow extends Render<Entity>
{
protected RenderShadow(RenderManager renderManager)
{
super(renderManager);
}
@Override
protected ResourceLocation getEntityTexture(Entity entity)
{
return null;
}
public void setShadowSize(float size)
{
this.shadowSize = size;
this.shadowOpaque = 0.8F;
}
}
} | 11,853 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityDirectorRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/tileentity/TileEntityDirectorRenderer.java | package mchorse.blockbuster.client.render.tileentity;
import mchorse.blockbuster.common.tileentity.TileEntityDirector;
import mchorse.mclib.client.Draw;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
public class TileEntityDirectorRenderer extends TileEntitySpecialRenderer<TileEntityDirector>
{
@Override
public void render(TileEntityDirector te, double x, double y, double z, float partialTicks, int destroyStage, float alpha)
{
Minecraft mc = Minecraft.getMinecraft();
/* Debug render (so people could find the block, lmao) */
if (mc.gameSettings.showDebugInfo && !mc.gameSettings.hideGUI)
{
int shader = GL11.glGetInteger(GL20.GL_CURRENT_PROGRAM);
if (shader != 0)
{
OpenGlHelper.glUseProgram(0);
}
GlStateManager.disableDepth();
GlStateManager.disableLighting();
GlStateManager.disableTexture2D();
GlStateManager.enableBlend();
Draw.cube(x + 0.25F, y + 0.25F, z + 0.25F, x + 0.75F, y + 0.75F, z + 0.75F, 1, 0, 0, 0.5F);
GlStateManager.disableBlend();
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.enableDepth();
if (shader != 0)
{
OpenGlHelper.glUseProgram(shader);
}
}
}
} | 1,633 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityGunItemStackRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/render/tileentity/TileEntityGunItemStackRenderer.java | package mchorse.blockbuster.client.render.tileentity;
import mchorse.blockbuster.client.KeyboardHandler;
import mchorse.blockbuster.client.RenderingHandler;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.utils.NBTUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Gun items's TEISR
*
* <p>This class is responsible for rendering gun items</p>
*/
@SideOnly(Side.CLIENT)
public class TileEntityGunItemStackRenderer extends TileEntityItemStackRenderer
{
/**
* A cache of model TEs
*/
public static final Map<ItemStack, GunEntry> models = new HashMap<ItemStack, GunEntry>();
private static boolean isRendering;
public static boolean isRendering()
{
return isRendering;
}
@Override
public void renderByItem(ItemStack stack, float partialTicks)
{
isRendering = true;
/* Thank you Mojang, very cool! */
partialTicks = Minecraft.getMinecraft().getRenderPartialTicks();
GunEntry model = models.get(stack);
if (model == null)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props != null)
{
model = new GunEntry(props);
models.put(stack, model);
}
}
if (model != null)
{
/*
* timer in ticks when to remove items that are not rendered anymore
* 5 should be enough to ensure that even with very low fps the model doesn't get removed unnecessarily
*/
model.timer = 5;
boolean firstPerson = RenderingHandler.itemTransformType == ItemCameraTransforms.TransformType.FIRST_PERSON_LEFT_HAND
|| RenderingHandler.itemTransformType == ItemCameraTransforms.TransformType.FIRST_PERSON_RIGHT_HAND;
if (
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.GUI &&
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND &&
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND &&
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.FIXED &&
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.GROUND
) {
if (!(KeyboardHandler.zoom.isKeyDown() && model.props.hideHandsOnZoom))
{
model.props.renderHands(RenderingHandler.getLastItemHolder(), partialTicks, firstPerson);
}
if (model.props.useZoomOverlayMorph && KeyboardHandler.zoom.isKeyDown())
{
model.props.renderZoomOverlay(RenderingHandler.getLastItemHolder(), partialTicks);
}
}
if (RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.GUI)
{
if (KeyboardHandler.zoom.isKeyDown() && model.props.hideHandsOnZoom)
{
if (
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.FIRST_PERSON_RIGHT_HAND &&
RenderingHandler.itemTransformType != ItemCameraTransforms.TransformType.FIRST_PERSON_LEFT_HAND
) {
model.props.render(RenderingHandler.getLastItemHolder(), partialTicks, firstPerson);
}
}
else
{
model.props.render(RenderingHandler.getLastItemHolder(), partialTicks, firstPerson);
}
}
if (RenderingHandler.itemTransformType == ItemCameraTransforms.TransformType.GUI)
{
if (model.props.useInventoryMorph && model.props.inventoryMorph != null)
{
model.props.renderInventoryMorph(RenderingHandler.getLastItemHolder(), partialTicks);
}
else
{
model.props.render(RenderingHandler.getLastItemHolder(), partialTicks, firstPerson);
}
}
this.reset();
}
isRendering = false;
}
public void reset()
{
Minecraft mc = Minecraft.getMinecraft();
TextureManager manager = mc.getTextureManager();
manager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
mc.getTextureMapBlocks().setBlurMipmapDirect(false, true);
mc.getTextureMapBlocks().setBlurMipmap(false, false);
}
public static class GunEntry
{
public int timer = 20;
public GunProps props;
public GunEntry(GunProps props)
{
this.props = props;
}
}
} | 5,305 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelVoxRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/ModelVoxRenderer.java | package mchorse.blockbuster.client.model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.api.formats.Mesh;
import mchorse.blockbuster.api.formats.obj.OBJParser;
import mchorse.blockbuster.api.formats.vox.MeshesVOX;
import mchorse.blockbuster.api.formats.vox.data.VoxTexture;
import mchorse.blockbuster.client.render.RenderCustomModel;
import mchorse.mclib.client.render.VertexBuilder;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
/**
* Like {@link ModelCustomRenderer}, this model renders
*/
@SideOnly(Side.CLIENT)
public class ModelVoxRenderer extends ModelCustomRenderer
{
public static final ResourceLocation VOXTEX = new ResourceLocation("blockbuster", "textures/dynamic_vox");
/**
* Mesh containing the data about the model
*/
public MeshesVOX mesh;
/**
* Vox palette texture
*/
public VoxTexture texture;
public ModelVoxRenderer(ModelCustom model, ModelLimb limb, ModelTransform transform, MeshesVOX mesh)
{
super(model, limb, transform);
this.mesh = mesh;
this.min = mesh.getMin();
this.max = mesh.getMax();
}
/**
* Instead of generating plain cube, this model renderer will
* generate mesh which was read by the {@link OBJParser}.
*/
@Override
protected void compileDisplayList(float scale)
{
if (this.mesh != null)
{
BufferBuilder renderer = Tessellator.getInstance().getBuffer();
/* Generate display list */
Mesh mesh = this.mesh.mesh;
{
int id = GLAllocation.generateDisplayLists(1);
GlStateManager.glNewList(id, GL11.GL_COMPILE);
renderer.begin(GL11.GL_TRIANGLES, VertexBuilder.getFormat(false, true, false, true));
for (int i = 0, c = mesh.triangles; i < c; i++)
{
float x = (mesh.posData[i * 3] - this.limb.origin[0]) / 16F;
float y = -(mesh.posData[i * 3 + 1] - this.limb.origin[1]) / 16F;
float z = (mesh.posData[i * 3 + 2] - this.limb.origin[2]) / 16F;
float u = mesh.texData[i * 2];
float v = mesh.texData[i * 2 + 1];
float nx = mesh.normData[i * 3];
float ny = -mesh.normData[i * 3 + 1];
float nz = mesh.normData[i * 3 + 2];
renderer.pos(x, y, z).tex(u, v).normal(nx, ny, nz).endVertex();
if (i % 3 == 2)
{
VertexBuilder.calcTangent(renderer, false);
}
}
Tessellator.getInstance().draw();
GlStateManager.glEndList();
this.displayList = id;
}
this.texture = new VoxTexture(this.mesh.document.palette, this.limb.specular);
this.compiled = true;
this.mesh = null;
}
else
{
super.compileDisplayList(scale);
}
}
/**
* Instead of rendering one default display list, this method
* renders the meshes
*/
@Override
protected void renderDisplayList()
{
if (this.texture != null)
{
TextureManager mgr = Minecraft.getMinecraft().getTextureManager();
mgr.loadTexture(VOXTEX, this.texture);
mgr.bindTexture(VOXTEX);
GL11.glCallList(this.displayList);
RenderCustomModel.bindLastTexture();
}
}
@Override
public void delete()
{
super.delete();
if (this.texture != null)
{
this.texture.deleteGlTexture();
this.texture = null;
}
}
} | 4,237 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelOBJRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/ModelOBJRenderer.java | package mchorse.blockbuster.client.model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.api.formats.obj.MeshOBJ;
import mchorse.blockbuster.api.formats.obj.MeshesOBJ;
import mchorse.blockbuster.api.formats.obj.OBJMaterial;
import mchorse.blockbuster.api.formats.obj.OBJParser;
import mchorse.blockbuster.api.formats.obj.ShapeKey;
import mchorse.blockbuster.client.render.RenderCustomModel;
import mchorse.blockbuster.client.textures.MipmapTexture;
import mchorse.mclib.client.render.VertexBuilder;
import mchorse.mclib.utils.Interpolations;
import mchorse.mclib.utils.ReflectionUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
/**
* Like {@link ModelCustomRenderer}, this model renders
*/
public class ModelOBJRenderer extends ModelCustomRenderer
{
/**
* Mesh containing the data about the model
*/
public MeshesOBJ mesh;
/**
* Display lists
*/
public OBJDisplayList[] displayLists;
/**
* Custom materials texture
*/
public Map<String, ResourceLocation> materials;
/**
* Shape configurations
*/
public List<ShapeKey> shapes;
/**
* Solid colored texture ID
*/
protected int solidColorTex = -1;
public ModelOBJRenderer(ModelCustom model, ModelLimb limb, ModelTransform transform, MeshesOBJ mesh)
{
super(model, limb, transform);
this.mesh = mesh;
this.min = mesh.getMin();
this.max = mesh.getMax();
}
/**
* Instead of generating plain cube, this model renderer will
* generate mesh which was read by the {@link OBJParser}.
*/
@Override
protected void compileDisplayList(float scale)
{
if (this.mesh != null)
{
this.displayLists = new OBJDisplayList[this.mesh.meshes.size()];
int index = 0;
int texture = 0;
int count = 0;
/* Generate a texture based on solid colored materials */
for (MeshOBJ mesh : this.mesh.meshes)
{
count += mesh.material != null && !mesh.material.useTexture ? 1 : 0;
}
if (count > 0)
{
ByteBuffer buffer = GLAllocation.createDirectByteBuffer(count * 4);
texture = GL11.glGenTextures();
for (MeshOBJ mesh : this.mesh.meshes)
{
if (mesh.material != null && !mesh.material.useTexture)
{
buffer.put((byte) (mesh.material.r * 255));
buffer.put((byte) (mesh.material.g * 255));
buffer.put((byte) (mesh.material.b * 255));
buffer.put((byte) 255);
}
}
buffer.flip();
/* For some reason, if there is no glTexParameter calls
* the texture becomes pure white */
GlStateManager.bindTexture(texture);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, count, 1, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
}
/* Generate display lists */
int j = 0;
int k = 0;
for (MeshOBJ mesh : this.mesh.meshes)
{
OBJMaterial material = mesh.material;
if (material != null && material.useTexture && material.texture != null)
{
this.setupTexture(material);
}
int id = GLAllocation.generateDisplayLists(1);
boolean hasColor = material != null && !mesh.material.useTexture;
BufferBuilder renderer = Tessellator.getInstance().getBuffer();
GlStateManager.glNewList(id, GL11.GL_COMPILE);
renderer.begin(GL11.GL_TRIANGLES, VertexBuilder.getFormat(false, true, false, true));
float texF = (j + 0.5F) / count;
for (int i = 0, c = mesh.triangles; i < c; i++)
{
float x = mesh.posData[i * 3] - this.limb.origin[0];
float y = -mesh.posData[i * 3 + 1] + this.limb.origin[1];
float z = mesh.posData[i * 3 + 2] - this.limb.origin[2];
float u = mesh.texData[i * 2];
float v = mesh.texData[i * 2 + 1];
float nx = mesh.normData[i * 3];
float ny = -mesh.normData[i * 3 + 1];
float nz = mesh.normData[i * 3 + 2];
if (!this.model.model.legacyObj)
{
x = -mesh.posData[i * 3] + this.limb.origin[0];
nx *= -1;
}
if (hasColor)
{
renderer.pos(x, y, z).tex(texF, 0.5F).normal(nx, ny, nz).endVertex();
}
else
{
renderer.pos(x, y, z).tex(u, v).normal(nx, ny, nz).endVertex();
}
if (i % 3 == 2)
{
VertexBuilder.calcTangent(renderer, false);
}
}
Tessellator.getInstance().draw();
GlStateManager.glEndList();
this.displayLists[index++] = new OBJDisplayList(k, id, texture, mesh, this.mesh.shapes == null);
j += hasColor ? 1 : 0;
k += 1;
}
this.compiled = true;
this.solidColorTex = texture;
/* Discard the mesh ONLY if there are no shapes */
if (this.mesh.shapes == null)
{
this.mesh = null;
}
}
else
{
super.compileDisplayList(scale);
}
}
/**
* Manually replace/setup a mipmapped texture
*/
private void setupTexture(OBJMaterial material)
{
TextureManager manager = Minecraft.getMinecraft().renderEngine;
ITextureObject texture = manager.getTexture(material.texture);
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(manager);
if (texture != null && !(texture instanceof MipmapTexture))
{
GlStateManager.deleteTexture(map.remove(material.texture).getGlTextureId());
texture = null;
}
if (texture == null)
{
try
{
/* Load texture manually */
texture = new MipmapTexture(material.texture);
texture.loadTexture(Minecraft.getMinecraft().getResourceManager());
map.put(material.texture, texture);
}
catch (Exception e)
{
System.err.println("An error occurred during loading manually a mipmap'd texture '" + material.texture + "'");
e.printStackTrace();
}
}
boolean loaded = texture instanceof MipmapTexture;
manager.bindTexture(material.texture);
int mod = material.linear ? (loaded ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_LINEAR) : (loaded ? GL11.GL_NEAREST_MIPMAP_LINEAR : GL11.GL_NEAREST);
int mag = material.linear ? GL11.GL_LINEAR : GL11.GL_NEAREST;
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, mod);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag);
}
/**
* Instead of rendering one default display list, this method
* renders the meshes
*/
@Override
protected void renderDisplayList()
{
for (OBJDisplayList list : this.displayLists)
{
boolean hasColor = list.material != null && !list.material.useTexture;
boolean hasTexture = list.material != null && list.material.useTexture;
if (hasColor)
{
GlStateManager.bindTexture(list.texId);
}
if (hasTexture && list.material.texture != null)
{
ResourceLocation texture = list.material.texture;
if (this.materials != null && this.materials.containsKey(list.material.name))
{
texture = this.materials.get(list.material.name);
}
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
}
list.render(this);
if (hasColor || (hasTexture && list.material.texture != null))
{
RenderCustomModel.bindLastTexture();
}
}
}
@Override
public void delete()
{
super.delete();
if (this.displayLists != null)
{
for (OBJDisplayList list : this.displayLists)
{
if (list.id != -1)
{
GL11.glDeleteLists(list.id, 1);
}
}
}
if (this.solidColorTex != -1)
{
GL11.glDeleteTextures(this.solidColorTex);
}
}
public static class OBJDisplayList
{
public int index;
public int id;
public int texId;
public OBJMaterial material;
private MeshOBJ mesh;
private MeshOBJ temporary;
public OBJDisplayList(int index, int id, int texId, MeshOBJ mesh, boolean discard)
{
this.index = index;
this.id = id;
this.texId = texId;
this.material = mesh.material;
if (!discard)
{
this.mesh = mesh;
this.temporary = new MeshOBJ(new float[mesh.posData.length], new float[mesh.texData.length], new float[mesh.normData.length]);
}
}
public void render(ModelOBJRenderer renderer)
{
if (renderer.shapes != null && !renderer.shapes.isEmpty() && this.mesh != null)
{
BufferBuilder builder = Tessellator.getInstance().getBuffer();
builder.begin(GL11.GL_TRIANGLES, VertexBuilder.getFormat(false, true, false, true));
// float texF = (j + 0.5F) / count;
for (int i = 0, c = this.mesh.triangles; i < c; i++)
{
this.temporary.posData[i * 3] = this.mesh.posData[i * 3];
this.temporary.posData[i * 3 + 1] = this.mesh.posData[i * 3 + 1];
this.temporary.posData[i * 3 + 2] = this.mesh.posData[i * 3 + 2];
this.temporary.texData[i * 2] = this.mesh.texData[i * 2];
this.temporary.texData[i * 2 + 1] = this.mesh.texData[i * 2 + 1];
this.temporary.normData[i * 3] = this.mesh.normData[i * 3];
this.temporary.normData[i * 3 + 1] = this.mesh.normData[i * 3 + 1];
this.temporary.normData[i * 3 + 2] = this.mesh.normData[i * 3 + 2];
}
for (ShapeKey key : renderer.shapes)
{
List<MeshOBJ> list = renderer.mesh.shapes.get(key.name);
if (list == null)
{
continue;
}
MeshOBJ mesh = list.get(this.index);
float factor = key.value;
if (mesh == null || this.temporary.triangles != mesh.triangles)
{
continue;
}
for (int i = 0, c = this.temporary.triangles; i < c; i++)
{
float x;
float y;
float z;
float u;
float v;
float nx = this.temporary.normData[i * 3];
float ny = this.temporary.normData[i * 3 + 1];
float nz = this.temporary.normData[i * 3 + 2];
if (key.relative)
{
/* final = temporary + lerp(initial, current, x) - initial */
x = this.temporary.posData[i * 3] + Interpolations.lerp(this.mesh.posData[i * 3], mesh.posData[i * 3], factor) - this.mesh.posData[i * 3];
y = this.temporary.posData[i * 3 + 1] + Interpolations.lerp(this.mesh.posData[i * 3 + 1], mesh.posData[i * 3 + 1], factor) - this.mesh.posData[i * 3 + 1];
z = this.temporary.posData[i * 3 + 2] + Interpolations.lerp(this.mesh.posData[i * 3 + 2], mesh.posData[i * 3 + 2], factor) - this.mesh.posData[i * 3 + 2];
u = this.temporary.texData[i * 2] + Interpolations.lerp(this.mesh.texData[i * 2], mesh.texData[i * 2], factor) - this.mesh.texData[i * 2];
v = this.temporary.texData[i * 2 + 1] + Interpolations.lerp(this.mesh.texData[i * 2 + 1], mesh.texData[i * 2 + 1], factor) - this.mesh.texData[i * 2 + 1];
}
else
{
x = Interpolations.lerp(this.temporary.posData[i * 3], mesh.posData[i * 3], factor);
y = Interpolations.lerp(this.temporary.posData[i * 3 + 1], mesh.posData[i * 3 + 1], factor);
z = Interpolations.lerp(this.temporary.posData[i * 3 + 2], mesh.posData[i * 3 + 2], factor);
u = Interpolations.lerp(this.temporary.texData[i * 2], mesh.texData[i * 2], factor);
v = Interpolations.lerp(this.temporary.texData[i * 2 + 1], mesh.texData[i * 2 + 1], factor);
}
if (
nx == mesh.normData[i * 3] &&
ny == mesh.normData[i * 3 + 1] &&
nz == mesh.normData[i * 3 + 2]
) {
nx = Interpolations.lerp(nx, mesh.normData[i * 3], factor);
ny = Interpolations.lerp(ny, mesh.normData[i * 3 + 1], factor);
nz = Interpolations.lerp(nz, mesh.normData[i * 3 + 2], factor);
}
this.temporary.posData[i * 3] = x;
this.temporary.posData[i * 3 + 1] = y;
this.temporary.posData[i * 3 + 2] = z;
this.temporary.texData[i * 2] = u;
this.temporary.texData[i * 2 + 1] = v;
this.temporary.normData[i * 3] = nx;
this.temporary.normData[i * 3 + 1] = ny;
this.temporary.normData[i * 3 + 2] = nz;
}
}
for (int i = 0, c = this.temporary.triangles; i < c; i++)
{
float x = this.temporary.posData[i * 3] - renderer.limb.origin[0];
float y = -this.temporary.posData[i * 3 + 1] + renderer.limb.origin[1];
float z = this.temporary.posData[i * 3 + 2] - renderer.limb.origin[2];
float u = this.temporary.texData[i * 2];
float v = this.temporary.texData[i * 2 + 1];
float nx = this.temporary.normData[i * 3];
float ny = -this.temporary.normData[i * 3 + 1];
float nz = this.temporary.normData[i * 3 + 2];
if (!renderer.model.model.legacyObj)
{
x = -this.temporary.posData[i * 3] + renderer.limb.origin[0];
nx *= -1;
}
if (false)
{
// renderer.pos(x, y, z).tex(texF, 0.5F).normal(nx, ny, nz).endVertex();
}
else
{
builder.pos(x, y, z).tex(u, v).normal(nx, ny, nz).endVertex();
}
if (i % 3 == 2)
{
VertexBuilder.calcTangent(builder, false);
}
}
Tessellator.getInstance().draw();
}
else
{
GL11.glCallList(this.id);
}
}
}
} | 17,204 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelCustom.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/ModelCustom.java | package mchorse.blockbuster.client.model;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb.Holding;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.api.formats.obj.ShapeKey;
import mchorse.blockbuster.client.KeyboardHandler;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.common.OrientedBB;
import mchorse.blockbuster.common.item.ItemGun;
import mchorse.blockbuster.utils.EntityUtils;
import mchorse.blockbuster.utils.NBTUtils;
import mchorse.blockbuster_pack.morphs.CustomMorph;
import mchorse.blockbuster_pack.morphs.CustomMorph.LimbProperties;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
/**
* Custom Model class
* <p>
* This class is responsible for managing available custom models that have
* been loaded from config folder or from server and also render a custom model
* itself.
*/
@SideOnly(Side.CLIENT)
public class ModelCustom extends ModelBiped
{
/**
* Repository of custom models that are available for usage
*/
public static final Map<String, ModelCustom> MODELS = new HashMap<String, ModelCustom>();
/**
* Model data
*/
public Model model;
/**
* Current pose
*/
public ModelPose pose;
public CustomMorph current;
/**
* Array of all limbs that has been parsed from JSON model
*/
public ModelCustomRenderer[] limbs;
/**
* Array of limbs that has to be rendered (child limbs doesn't have to
* be rendered, because they're getting render call from parent).
*/
public ModelCustomRenderer[] renderable;
public ModelCustomRenderer[] left;
public ModelCustomRenderer[] right;
public ModelCustomRenderer[] armor;
public Map<String, ResourceLocation> materials;
public List<ShapeKey> shapes;
/**
* Initiate the model with the size of the texture
*/
public ModelCustom(Model model)
{
this.model = model;
this.textureWidth = model.texture[0];
this.textureHeight = model.texture[1];
}
/**
* Get the {@link ModelCustomRenderer} for the provided limb name
* @param name
* @return the {@link ModelCustomRenderer} instance that has the limb with the same name as the provided String
*/
public ModelCustomRenderer get(String name)
{
for (ModelCustomRenderer renderer : this.limbs)
{
if (renderer.limb.name.equals(name))
{
return renderer;
}
}
return null;
}
@Override
public void render(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale)
{
boolean keying = this.current != null && this.current.keying;
GlStateManager.enableBlend();
if (keying)
{
GlStateManager.glBlendEquation(GL14.GL_FUNC_REVERSE_SUBTRACT);
GlStateManager.blendFunc(GL11.GL_ZERO, GL11.GL_ZERO);
}
else
{
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
}
if (this.current != null)
{
for (List<OrientedBB> obbs : this.current.orientedBBlimbs.values())
{
for (OrientedBB obb : obbs)
{
obb.center.set(entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * Minecraft.getMinecraft().getRenderPartialTicks(),
entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * Minecraft.getMinecraft().getRenderPartialTicks(),
entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * Minecraft.getMinecraft().getRenderPartialTicks());
}
}
}
for (ModelRenderer limb : this.renderable)
{
limb.render(scale);
}
if (keying)
{
GlStateManager.glBlendEquation(GL14.GL_FUNC_ADD);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
}
GlStateManager.disableBlend();
this.current = null;
}
public void renderForStencil(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale)
{
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
for (int i = 0; i < this.limbs.length; i++)
{
this.limbs[i].setupStencilRendering(i + 1);
}
for (ModelRenderer limb : this.renderable)
{
limb.render(scale);
}
GlStateManager.disableBlend();
}
/**
* Set hands postures
*/
public void setHands(EntityLivingBase entity)
{
ItemStack rightItem = entity.getHeldItemMainhand();
ItemStack leftItem = entity.getHeldItemOffhand();
ModelBiped.ArmPose right = ModelBiped.ArmPose.EMPTY;
ModelBiped.ArmPose left = ModelBiped.ArmPose.EMPTY;
if (!rightItem.isEmpty())
{
right = ModelBiped.ArmPose.ITEM;
if (entity.getItemInUseCount() > 0)
{
EnumAction enumaction = rightItem.getItemUseAction();
if (enumaction == EnumAction.BLOCK)
{
right = ModelBiped.ArmPose.BLOCK;
}
else if (enumaction == EnumAction.BOW)
{
right = ModelBiped.ArmPose.BOW_AND_ARROW;
}
}
if (rightItem.getItem() instanceof ItemGun)
{
GunProps props = NBTUtils.getGunProps(rightItem);
if (props.alwaysArmsShootingPose)
{
right = ModelBiped.ArmPose.BOW_AND_ARROW;
}
else if (props.enableArmsShootingPose && KeyboardHandler.gunShoot.isKeyDown())
{
right = ModelBiped.ArmPose.BOW_AND_ARROW;
}
}
}
if (!leftItem.isEmpty())
{
left = ModelBiped.ArmPose.ITEM;
if (entity.getItemInUseCount() > 0)
{
EnumAction action = leftItem.getItemUseAction();
if (action == EnumAction.BLOCK)
{
left = ModelBiped.ArmPose.BLOCK;
}
}
}
this.rightArmPose = right;
this.leftArmPose = left;
}
/**
* This method is responsible for setting gameplay wise features like head
* looking, idle rotating (like arm swinging), swinging and swiping
*/
@Override
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn)
{
if (entityIn instanceof EntityLivingBase)
{
this.setHands((EntityLivingBase) entityIn);
}
else
{
this.leftArmPose = ArmPose.EMPTY;
this.rightArmPose = ArmPose.EMPTY;
}
for (ModelCustomRenderer limb : this.limbs)
{
boolean mirror = limb.limb.mirror;
boolean invert = limb.limb.invert;
if (limb instanceof ModelOBJRenderer)
{
ModelOBJRenderer obj = (ModelOBJRenderer) limb;
obj.materials = this.materials;
obj.shapes = this.shapes;
}
float factor = mirror ^ invert ? -1 : 1;
float PI = (float) Math.PI;
/* Reseting the angles */
float anim = this.applyLimbPose(limb);
float rotateX = limb.rotateAngleX;
float rotateY = limb.rotateAngleY;
float rotateZ = limb.rotateAngleZ;
if (limb.limb.cape && entityIn instanceof EntityLivingBase && this.current != null)
{
float partialTicks = Minecraft.getMinecraft().getRenderPartialTicks();
EntityLivingBase living = (EntityLivingBase) entityIn;
double dX = this.current.prevCapeX + (this.current.capeX - this.current.prevCapeX) * partialTicks - (living.prevPosX + (living.posX - living.prevPosX) * partialTicks);
double dY = this.current.prevCapeY + (this.current.capeY - this.current.prevCapeY) * partialTicks - (living.prevPosY + (living.posY - living.prevPosY) * partialTicks);
double dZ = this.current.prevCapeZ + (this.current.capeZ - this.current.prevCapeZ) * partialTicks - (living.prevPosZ + (living.posZ - living.prevPosZ) * partialTicks);
float bodyYaw = living.prevRenderYawOffset + (living.renderYawOffset - living.prevRenderYawOffset) * partialTicks;
double sin = MathHelper.sin(bodyYaw / 180 * PI);
double cos = -MathHelper.cos(bodyYaw / 180 * PI);
float h = (float) MathHelper.clamp(dY * 10.0F, -6.0F, 32.0F);
float pitch = (float) (dX * sin + dZ * cos) * 100.0F;
float yaw = (float) (dX * cos - dZ * sin) * 100.0F;
if (pitch > 0.0F)
{
pitch = -pitch;
}
float cameraYaw = 0;
if (living instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) living;
cameraYaw = player.prevCameraYaw + (player.cameraYaw - player.prevCameraYaw) * partialTicks;
}
h += MathHelper.sin((living.prevDistanceWalkedModified + (living.distanceWalkedModified - living.prevDistanceWalkedModified) * partialTicks) * 6.0F) * 32.0F * cameraYaw;
limb.rotateAngleX += (6.0F + pitch / 2.0F + h) / 180 * PI;
limb.rotateAngleY += (yaw / 2.0F * 0) / 180 * PI;
}
if ((limb.limb.lookX || limb.limb.lookY) && !limb.limb.wheel)
{
if (limb.limb.lookX)
{
limb.rotateAngleX += headPitch * 0.017453292F;
}
if (limb.limb.lookY)
{
if (invert)
{
limb.rotateAngleZ += netHeadYaw * 0.017453292F;
}
else
{
limb.rotateAngleY += netHeadYaw * 0.017453292F;
}
}
}
if (limb.limb.swinging)
{
boolean flag = entityIn instanceof EntityLivingBase && ((EntityLivingBase) entityIn).getTicksElytraFlying() > 4;
float f = 1.0F;
if (flag)
{
f = (float) (entityIn.motionX * entityIn.motionX + entityIn.motionY * entityIn.motionY + entityIn.motionZ * entityIn.motionZ);
f = f / 0.2F;
f = f * f * f;
}
if (f < 1.0F)
{
f = 1.0F;
}
float f2 = mirror ^ invert ? 1 : 0;
float f3 = limb.limb.holding == Holding.NONE ? 1.4F : 1.0F;
limb.rotateAngleX += MathHelper.cos(limbSwing * 0.6662F + PI * f2) * f3 * limbSwingAmount / f;
}
if (limb.limb.idle)
{
limb.rotateAngleZ += (MathHelper.cos(ageInTicks * 0.09F) * 0.05F + 0.05F) * factor;
limb.rotateAngleX += (MathHelper.sin(ageInTicks * 0.067F) * 0.05F) * factor;
}
if (limb.limb.swiping && !limb.limb.wing && this.swingProgress > 0.0F)
{
float swing = this.swingProgress;
float bodyY = MathHelper.sin(MathHelper.sqrt(swing) * PI * 2F) * 0.2F;
swing = 1.0F - swing;
swing = swing * swing * swing;
swing = 1.0F - swing;
float sinSwing = MathHelper.sin(swing * PI);
float sinSwing2 = MathHelper.sin(this.swingProgress * PI) * -(0.0F - 0.7F) * 0.75F;
limb.rotateAngleX = limb.rotateAngleX - (sinSwing * 1.2F + sinSwing2);
limb.rotateAngleY += bodyY * 2.0F * factor;
limb.rotateAngleZ += MathHelper.sin(this.swingProgress * PI) * -0.4F * factor;
}
if (limb.limb.holding != Holding.NONE)
{
boolean right = limb.limb.holding == Holding.RIGHT;
ModelBiped.ArmPose pose = right ? this.rightArmPose : this.leftArmPose;
ModelBiped.ArmPose opposite = right ? this.leftArmPose : this.rightArmPose;
switch (pose)
{
case BLOCK:
limb.rotateAngleX = limb.rotateAngleX * 0.5F - 0.9424779F;
limb.rotateAngleY = 0.5235988F * (right ? -1 : 1);
break;
case ITEM:
if (limb.limb.hold)
{
limb.rotateAngleX = limb.rotateAngleX * 0.5F - PI / 10F;
}
break;
}
float rotateAngleX = headPitch * 0.017453292F;
float rotateAngleY = netHeadYaw * 0.017453292F;
if (right && pose == ModelBiped.ArmPose.BOW_AND_ARROW)
{
limb.rotateAngleY = -0.1F + rotateAngleY - 0.4F;
limb.rotateAngleY = 0.1F + rotateAngleY;
limb.rotateAngleX = -((float) Math.PI / 2F) + rotateAngleX;
limb.rotateAngleX = -((float) Math.PI / 2F) + rotateAngleX;
}
else if (!right && opposite == ModelBiped.ArmPose.BOW_AND_ARROW)
{
limb.rotateAngleY = -0.1F + rotateAngleY;
limb.rotateAngleY = 0.1F + rotateAngleY + 0.4F;
limb.rotateAngleX = -((float) Math.PI / 2F) + rotateAngleX;
limb.rotateAngleX = -((float) Math.PI / 2F) + rotateAngleX;
}
}
if (limb.limb.wheel)
{
limb.rotateAngleX += limbSwing * factor;
if (limb.limb.lookY)
{
limb.rotateAngleY = netHeadYaw / 180 * (float) Math.PI;
}
}
if (limb.limb.wing)
{
float wingFactor = MathHelper.cos(ageInTicks * 1.3F) * (float) Math.PI * 0.25F * (0.5F + limbSwingAmount) * factor;
if (limb.limb.swiping)
{
limb.rotateAngleZ = wingFactor;
}
else
{
limb.rotateAngleY = wingFactor;
}
}
if (limb.limb.roll)
{
limb.rotateAngleZ += -EntityUtils.getRoll(entityIn, ageInTicks % 1) / 180F * PI;
}
limb.rotateAngleX = (limb.rotateAngleX - rotateX) * anim + rotateX;
limb.rotateAngleY = (limb.rotateAngleY - rotateY) * anim + rotateY;
limb.rotateAngleZ = (limb.rotateAngleZ - rotateZ) * anim + rotateZ;
}
}
/**
* Apply transform from current pose on given limb
*/
public float applyLimbPose(ModelCustomRenderer limb)
{
ModelTransform trans = this.pose.limbs.get(limb.limb.name);
limb.applyTransform(trans == null ? ModelTransform.DEFAULT : trans);
if (trans instanceof LimbProperties)
{
return 1F - ((LimbProperties) trans).fixed;
}
return 1F;
}
/**
* Get renderer for an arm
*/
public ModelCustomRenderer[] getRenderForArm(EnumHandSide side)
{
if (side == EnumHandSide.LEFT)
{
return this.left;
}
else if (side == EnumHandSide.RIGHT)
{
return this.right;
}
return null;
}
/**
* Clean up resources used by this model
*/
public void delete()
{
for (ModelCustomRenderer renderer : this.limbs)
{
renderer.delete();
}
}
} | 17,132 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelCustomRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/ModelCustomRenderer.java | package mchorse.blockbuster.client.model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.client.model.parsing.ModelExtrudedLayer;
import mchorse.blockbuster.client.render.RenderCustomModel;
import mchorse.blockbuster.common.OrientedBB;
import mchorse.blockbuster_pack.morphs.CustomMorph.LimbProperties;
import mchorse.mclib.utils.MatrixUtils;
import mchorse.metamorph.bodypart.BodyPart;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import javax.vecmath.Matrix3f;
import javax.vecmath.Vector3f;
/**
* Custom model renderer class
*
* This class extended only for purpose of storing more
*/
@SideOnly(Side.CLIENT)
public class ModelCustomRenderer extends ModelRenderer
{
private static float lastBrightnessX;
private static float lastBrightnessY;
public ModelLimb limb;
public ModelTransform trasnform;
public ModelCustomRenderer parent;
public ModelCustom model;
public Vector3f cachedTranslation = new Vector3f();
/**
* At the moment no use -> would be useful to have realistic physics
* for every limb, see robotics https://www.tu-chemnitz.de/informatik/KI/edu/robotik/ws2017/vel.kin.pdf
*/
public Vector3f angularVelocity = new Vector3f();
public float scaleX = 1;
public float scaleY = 1;
public float scaleZ = 1;
/* Compied code from the ModelRenderer */
protected boolean compiled;
protected int displayList = -1;
/* Stencil magic */
public int stencilIndex = -1;
public boolean stencilRendering = false;
public Vector3f min;
public Vector3f max;
public ModelCustomRenderer(ModelCustom model, int texOffX, int texOffY)
{
super(model, texOffX, texOffY);
this.model = model;
}
/**
* Initiate with limb and transform instances
*/
public ModelCustomRenderer(ModelCustom model, ModelLimb limb, ModelTransform transform)
{
this(model, limb.texture[0], limb.texture[1]);
this.limb = limb;
this.trasnform = transform;
}
public void setupStencilRendering(int stencilIndex)
{
this.stencilIndex = stencilIndex;
this.stencilRendering = true;
}
/**
* Apply transformations on this model renderer
*/
public void applyTransform(ModelTransform transform)
{
this.trasnform = transform;
float x = transform.translate[0];
float y = transform.translate[1];
float z = transform.translate[2];
this.rotationPointX = x;
this.rotationPointY = this.limb.parent.isEmpty() ? (-y + 24) : -y;
this.rotationPointZ = -z;
this.rotateAngleX = transform.rotate[0] * (float) Math.PI / 180;
this.rotateAngleY = -transform.rotate[1] * (float) Math.PI / 180;
this.rotateAngleZ = -transform.rotate[2] * (float) Math.PI / 180;
this.scaleX = transform.scale[0];
this.scaleY = transform.scale[1];
this.scaleZ = transform.scale[2];
}
@Override
public void addChild(ModelRenderer renderer)
{
if (renderer instanceof ModelCustomRenderer)
{
((ModelCustomRenderer) renderer).parent = this;
}
super.addChild(renderer);
}
/**
* Setup state for current limb
*/
protected void setup()
{
GlStateManager.color(this.limb.color[0], this.limb.color[1], this.limb.color[2], this.limb.opacity);
lastBrightnessX = OpenGlHelper.lastBrightnessX;
lastBrightnessY = OpenGlHelper.lastBrightnessY;
if (!this.limb.lighting)
{
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240, lastBrightnessY);
}
if (this.trasnform instanceof LimbProperties)
{
LimbProperties limb = (LimbProperties) this.trasnform;
GlStateManager.color(limb.color.r, limb.color.g, limb.color.b, limb.color.a);
limb.applyGlow(lastBrightnessX, lastBrightnessY);
}
if (!this.limb.shading)
{
RenderHelper.disableStandardItemLighting();
}
if (this.limb.smooth)
{
GL11.glShadeModel(GL11.GL_SMOOTH);
}
}
/**
* Roll back the state to the way it was
*/
protected void disable()
{
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, lastBrightnessX, lastBrightnessY);
if (!this.limb.shading)
{
GlStateManager.enableLighting();
GlStateManager.enableLight(0);
GlStateManager.enableLight(1);
GlStateManager.enableColorMaterial();
}
if (this.limb.smooth)
{
GL11.glShadeModel(GL11.GL_FLAT);
}
}
@Override
@SideOnly(Side.CLIENT)
public void render(float scale)
{
if (!this.isHidden)
{
if (this.showModel)
{
GlStateManager.alphaFunc(GL11.GL_GREATER, 0);
if (!this.compiled)
{
this.compileDisplayList(scale);
}
MatrixUtils.Transformation modelView = new MatrixUtils.Transformation();
if (MatrixUtils.matrix != null)
{
modelView = MatrixUtils.extractTransformations(MatrixUtils.matrix, MatrixUtils.readModelView(BodyPart.modelViewMatrix));
}
this.cachedTranslation.set(this.rotationPointX/16,(this.limb.parent.isEmpty() ? this.rotationPointY -24 : this.rotationPointY)/16,this.rotationPointZ/16);
Matrix3f transformation = new Matrix3f(modelView.getRotation3f());
transformation.mul(modelView.getScale3f());
transformation.transform(this.cachedTranslation);
if (this.parent!=null)
{
this.cachedTranslation.add(this.parent.cachedTranslation);
}
if (this.model.current != null)
{
this.cachedTranslation.add(this.model.current.cachedTranslation);
this.model.current.cachedTranslation.scale(0);
}
//currently deactivated, only use bodypart's translation as radius for angular stuff
//BodyPart.cachedTranslation.set(this.cachedTranslation);
GlStateManager.pushMatrix();
GlStateManager.translate(this.offsetX, this.offsetY, this.offsetZ);
if (this.rotateAngleX == 0.0F && this.rotateAngleY == 0.0F && this.rotateAngleZ == 0.0F)
{
if (this.rotationPointX == 0.0F && this.rotationPointY == 0.0F && this.rotationPointZ == 0.0F)
{
GlStateManager.scale(this.scaleX, this.scaleY, this.scaleZ);
this.renderRenderer();
if (this.childModels != null)
{
for (int k = 0; k < this.childModels.size(); ++k)
{
this.childModels.get(k).render(scale);
}
}
updateObbs();
}
else
{
GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, this.rotationPointZ * scale);
GlStateManager.scale(this.scaleX, this.scaleY, this.scaleZ);
this.renderRenderer();
if (this.childModels != null)
{
for (int j = 0; j < this.childModels.size(); ++j)
{
this.childModels.get(j).render(scale);
}
}
updateObbs();
GlStateManager.translate(-this.rotationPointX * scale, -this.rotationPointY * scale, -this.rotationPointZ * scale);
}
}
else
{
GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, this.rotationPointZ * scale);
if (this.rotateAngleZ != 0.0F)
{
GlStateManager.rotate(this.rotateAngleZ * (180F / (float) Math.PI), 0.0F, 0.0F, 1.0F);
}
if (this.rotateAngleY != 0.0F)
{
GlStateManager.rotate(this.rotateAngleY * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F);
}
if (this.rotateAngleX != 0.0F)
{
GlStateManager.rotate(this.rotateAngleX * (180F / (float) Math.PI), 1.0F, 0.0F, 0.0F);
}
GlStateManager.scale(this.scaleX, this.scaleY, this.scaleZ);
this.renderRenderer();
if (this.childModels != null)
{
for (int i = 0; i < this.childModels.size(); ++i)
{
this.childModels.get(i).render(scale);
}
}
updateObbs();
}
GlStateManager.translate(-this.offsetX, -this.offsetY, -this.offsetZ);
GlStateManager.popMatrix();
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.1F);
}
}
}
public void updateObbs()
{
if(this.model != null && this.model.current != null && this.model.current.orientedBBlimbs != null )
{
if(this.model.current.orientedBBlimbs.get(this.limb) != null)
{
for(OrientedBB obb : this.model.current.orientedBBlimbs.get(this.limb))
{
if (MatrixUtils.matrix != null)
{
MatrixUtils.Transformation modelView = MatrixUtils.extractTransformations(MatrixUtils.matrix, MatrixUtils.readModelView(OrientedBB.modelView));
obb.rotation.set(modelView.getRotation3f());
obb.offset.set(modelView.getTranslation3f());
obb.scale.set(modelView.getScale3f());
}
obb.buildCorners();
}
}
}
}
@Override
@SideOnly(Side.CLIENT)
public void renderWithRotation(float scale)
{
if (!this.isHidden)
{
if (this.showModel)
{
if (!this.compiled)
{
this.compileDisplayList(scale);
}
GlStateManager.pushMatrix();
GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, this.rotationPointZ * scale);
if (this.rotateAngleY != 0.0F)
{
GlStateManager.rotate(this.rotateAngleY * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F);
}
if (this.rotateAngleX != 0.0F)
{
GlStateManager.rotate(this.rotateAngleX * (180F / (float) Math.PI), 1.0F, 0.0F, 0.0F);
}
if (this.rotateAngleZ != 0.0F)
{
GlStateManager.rotate(this.rotateAngleZ * (180F / (float) Math.PI), 0.0F, 0.0F, 1.0F);
}
GlStateManager.scale(this.scaleX, this.scaleY, this.scaleZ);
this.renderRenderer();
GlStateManager.popMatrix();
}
}
}
/**
* Allows the changing of Angles after a box has been rendered
*/
@Override
@SideOnly(Side.CLIENT)
public void postRender(float scale)
{
if (this.parent != null)
{
this.parent.postRender(scale);
}
if (!this.isHidden)
{
if (this.showModel)
{
if (!this.compiled)
{
this.compileDisplayList(scale);
}
if (this.rotateAngleX == 0.0F && this.rotateAngleY == 0.0F && this.rotateAngleZ == 0.0F)
{
if (this.rotationPointX != 0.0F || this.rotationPointY != 0.0F || this.rotationPointZ != 0.0F)
{
GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, this.rotationPointZ * scale);
}
}
else
{
GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, this.rotationPointZ * scale);
if (this.rotateAngleZ != 0.0F)
{
GlStateManager.rotate(this.rotateAngleZ * (180F / (float) Math.PI), 0.0F, 0.0F, 1.0F);
}
if (this.rotateAngleY != 0.0F)
{
GlStateManager.rotate(this.rotateAngleY * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F);
}
if (this.rotateAngleX != 0.0F)
{
GlStateManager.rotate(this.rotateAngleX * (180F / (float) Math.PI), 1.0F, 0.0F, 0.0F);
}
}
GlStateManager.scale(this.scaleX, this.scaleY, this.scaleZ);
}
}
}
/**
* Compiles a GL display list for this model
*/
protected void compileDisplayList(float scale)
{
this.displayList = GLAllocation.generateDisplayLists(1);
GlStateManager.glNewList(this.displayList, 4864);
BufferBuilder vertexbuffer = Tessellator.getInstance().getBuffer();
for (int i = 0; i < this.cubeList.size(); ++i)
{
this.cubeList.get(i).render(vertexbuffer, scale);
}
GlStateManager.glEndList();
this.compiled = true;
}
protected void renderRenderer()
{
if (this.limb.opacity <= 0 || this.trasnform instanceof LimbProperties && ((LimbProperties) this.trasnform).color.a <= 0)
{
return;
}
if (this.stencilRendering)
{
GL11.glStencilFunc(GL11.GL_ALWAYS, this.stencilIndex, -1);
this.stencilRendering = false;
}
this.setup();
this.renderDisplayList();
this.disable();
}
/**
* Render display list
*/
protected void renderDisplayList()
{
if (this.limb.is3D)
{
ModelExtrudedLayer.render3DLayer(this, RenderCustomModel.lastTexture);
}
else
{
GL11.glCallList(this.displayList);
}
}
/**
* DELET DIS
*/
public void delete()
{
if (this.displayList != -1)
{
GL11.glDeleteLists(this.displayList, 1);
}
}
} | 15,650 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelExporterOBJ.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/parsing/ModelExporterOBJ.java | package mchorse.blockbuster.client.model.parsing;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.vecmath.Matrix3f;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.ModelTransform;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.PositionTextureVertex;
import net.minecraft.client.model.TexturedQuad;
import net.minecraft.util.math.Vec3d;
/**
* Model exporter OBJ class
*
* <i>slaps roof of ModelExporterOBJ</i> this bad boy can convert so much
* OBJ models from Blockbuster JSON models.
*/
public class ModelExporterOBJ
{
private Model data;
private ModelPose pose;
public ModelExporterOBJ(Model data, ModelPose pose)
{
this.data = data;
this.pose = pose;
}
/**
* Export given model into OBJ string
*/
public String export(String modelName)
{
String obj = "# OBJ generated by Blockbuster (version " + Blockbuster.VERSION + ")\n\nmtllib " + modelName + ".mtl\nusemtl default\n";
Map<ModelLimb, Mesh> meshes = new HashMap<>();
this.generateMeshes(meshes);
return obj + this.generateBody(meshes);
}
/**
* Find texture quads field in {@link ModelBox} class.
*/
private Field findField()
{
Field field = null;
for (Field f : ModelBox.class.getDeclaredFields())
{
if (f.getType().equals(TexturedQuad[].class))
{
field = f;
field.setAccessible(true);
return field;
}
}
return null;
}
/**
* Prepare and generate meshes. This method is responsible for
* turning model's limbs into boxes and also preparing
* transformation matrices for actual generation of OBJ geometry.
*/
private void generateMeshes(Map<ModelLimb, Mesh> meshes)
{
ModelBase base = new ModelBase()
{};
base.textureWidth = this.data.texture[0];
base.textureHeight = this.data.texture[1];
for (ModelLimb limb : this.data.limbs.values())
{
ModelTransform transform = this.pose.limbs.get(limb.name);
if (transform == null)
{
transform = ModelTransform.DEFAULT;
}
Matrix4f mat = new Matrix4f();
mat.setIdentity();
Matrix3f rotScale = new Matrix3f();
rotScale.setIdentity();
mat.setTranslation(new Vector3f(transform.translate));
mat.m23 = -mat.m23;
mat.m13 = -mat.m13;
Matrix3f x = new Matrix3f();
rotScale.m00 = transform.scale[0];
rotScale.m11 = transform.scale[1];
rotScale.m22 = transform.scale[2];
Matrix3f rot = new Matrix3f();
rot.setIdentity();
x.setIdentity();
x.rotZ((float) Math.toRadians(-transform.rotate[2]));
rot.mul(x);
x.setIdentity();
x.rotY((float) Math.toRadians(-transform.rotate[1]));
rot.mul(x);
x.setIdentity();
x.rotX((float) Math.toRadians(transform.rotate[0]));
rot.mul(x);
rotScale.mul(rot);
mat.setRotationScale(rotScale);
int w = limb.size[0];
int h = limb.size[1];
int d = limb.size[2];
float ox = 1 - limb.anchor[0];
float oy = limb.anchor[1];
float oz = limb.anchor[2];
ModelBox box = new ModelBox(new ModelRenderer(base), limb.texture[0], limb.texture[1], -w * ox, -h * oy, -d * oz, w, h, d, limb.sizeOffset, limb.mirror);
meshes.put(limb, new Mesh(box, mat, rot));
}
}
/**
* Generate body of the OBJ file based on given prepared meshes
*/
private String generateBody(Map<ModelLimb, Mesh> meshes)
{
String output = "";
Field field = this.findField();
/* Count of vertices, normals and UVs indices */
int v = 1;
int u = 1;
int n = 1;
Matrix4f scale = new Matrix4f();
scale.setIdentity();
scale.rotZ((float) Math.PI);
scale.setScale(1 / 16F);
for (Map.Entry<ModelLimb, Mesh> entry : meshes.entrySet())
{
TexturedQuad[] quads = null;
ModelLimb limb = entry.getKey();
Mesh mesh = entry.getValue();
try
{
quads = (TexturedQuad[]) field.get(mesh.box);
}
catch (Exception e)
{}
/* Technically shouldn't ever happen, but just in case */
if (quads == null) continue;
Matrix4f mat = new Matrix4f(mesh.mat);
Matrix3f rot = new Matrix3f(mesh.rot);
if (!limb.parent.isEmpty())
{
ModelLimb parent = this.data.limbs.get(limb.parent);
while (parent != null)
{
Mesh parentMesh = meshes.get(parent);
Matrix4f mat2 = new Matrix4f(parentMesh.mat);
Matrix3f rot2 = new Matrix3f(parentMesh.rot);
mat2.mul(mat);
rot2.mul(rot);
mat = mat2;
rot = rot2;
parent = this.data.limbs.get(parent.parent);
}
}
/* Downscale geometry and flip vertically */
Matrix4f m = new Matrix4f(scale);
m.mul(mat);
mat = m;
/* Flip vertically normals */
Matrix3f r = new Matrix3f();
r.setIdentity();
r.m11 = -1;
r.mul(rot);
rot = r;
output += "o " + limb.name.replaceAll("\\s", "_") + "\n";
String vertices = "";
String normals = "";
String uvs = "";
String faces = "";
/* List of already added vectors, so we could make connected
* vertices, instead of separate faces (i.e. to simplify the work
* on the modeler to do the remove doubles on every limb) */
List<Vector4f> vecs = new ArrayList<Vector4f>();
for (TexturedQuad quad : quads)
{
/* Calculating normal as done in TexturedQuad */
Vec3d v1 = quad.vertexPositions[1].vector3D.subtractReverse(quad.vertexPositions[0].vector3D);
Vec3d v2 = quad.vertexPositions[1].vector3D.subtractReverse(quad.vertexPositions[2].vector3D);
Vec3d v3 = v2.crossProduct(v1).normalize();
Vector3f normal = new Vector3f((float) v3.x, (float) v3.y, (float) v3.z);
String face = "f ";
rot.transform(normal);
normal.normalize();
normals += String.format("vn %.4f %.4f %.4f\n", normal.x, normal.y, normal.z);
/* We're iterating backward, because it's important for
* normal generation. */
for (int i = 0; i < quad.nVertices; i++)
{
PositionTextureVertex vx = quad.vertexPositions[i];
Vector4f vec = new Vector4f((float) vx.vector3D.x, (float) vx.vector3D.y, (float) vx.vector3D.z, 1);
mat.transform(vec);
/* Find vector index */
int vi = vecs.indexOf(vec);
if (vi == -1)
{
/* If vector index is not found, add it and write it */
vertices += String.format("v %.4f %.4f %.4f\n", vec.x, vec.y, vec.z);
vi = vecs.size();
vecs.add(vec);
}
uvs += String.format("vt %f %f\n", vx.texturePositionX, 1 - vx.texturePositionY);
face += (v + vi) + "/" + u + "/" + n + " ";
u++;
}
faces += face.trim() + "\n";
n++;
}
v += vecs.size();
output += vertices + normals + uvs + faces;
}
return output;
}
/**
* Temporary mesh structure which is used internally within this
* class for generating an OBJ
*/
public static class Mesh
{
public ModelBox box;
public Matrix4f mat;
public Matrix3f rot;
public Mesh(ModelBox box, Matrix4f mat, Matrix3f rot)
{
this.box = box;
this.mat = mat;
this.rot = rot;
}
}
} | 8,998 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelExtrudedLayer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/parsing/ModelExtrudedLayer.java | package mchorse.blockbuster.client.model.parsing;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import mchorse.mclib.McLib;
import mchorse.mclib.client.render.VertexBuilder;
import mchorse.mclib.utils.MathUtils;
import mchorse.mclib.utils.resources.MultiResourceLocation;
import mchorse.mclib.utils.resources.MultiskinThread;
import mchorse.mclib.utils.resources.TextureProcessor;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Model extruded layer class
*
* This baby is responsible for making wonders. Basically, it allows
* to render extruded layers based on the texture.
*
* TODO: Clean up and make sure the code isn't confusing (axes and coordinates)
*/
public class ModelExtrudedLayer
{
public static final byte TOP_BIT = 0b1;
public static final byte BOTTOM_BIT = 0b10;
public static final byte FRONT_BIT = 0b100;
public static final byte BACK_BIT = 0b1000;
public static final byte LEFT_BIT = 0b10000;
public static final byte RIGHT_BIT = 0b100000;
/**
* Storage for extruded layers
*/
protected static Map<ModelCustomRenderer, Map<ResourceLocation, Integer>> layers = new HashMap<>();
/**
* Cached textures
*/
protected static Map<ResourceLocation, CachedImage> images = new HashMap<>();
public static void forceReload(ResourceLocation location, BufferedImage image)
{
CachedImage cached = new CachedImage(image);
cached.timer = Integer.MAX_VALUE;
images.put(location, cached);
}
/**
* Render the extruded 3D layer. If extruded layer wasn't generated
* before, it will generate it.
*/
public static void render3DLayer(ModelCustomRenderer renderer, ResourceLocation texture)
{
Map<ResourceLocation, Integer> map = layers.get(renderer);
int id = -1;
if (map == null)
{
map = new HashMap<>();
layers.put(renderer, map);
}
if (!map.containsKey(texture))
{
generateLayer(renderer, texture, map);
}
Integer callId = map.get(texture);
if (callId != null)
{
id = callId;
}
if (id != -1)
{
// GlStateManager.disableTexture2D();
// GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
GL11.glCallList(id);
// GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
// GlStateManager.enableTexture2D();
}
}
/**
* Tick the cache to clean up the data
*/
public static void tickCache()
{
/* Clean up cache */
if (!images.isEmpty())
{
Iterator<CachedImage> it = images.values().iterator();
while (it.hasNext())
{
CachedImage image = it.next();
if (image.timer <= 0)
{
image.image.flush();
it.remove();
}
image.timer -= 1;
}
}
}
/**
* Generate extruded layer call list for given limb renderer and
* texture location
*/
private static void generateLayer(ModelCustomRenderer renderer, ResourceLocation texture, Map<ResourceLocation, Integer> map)
{
int id = -1;
try
{
CachedImage image = images.get(texture);
if (image == null)
{
/* Multi-threaded multi-skins freak out when gerResource(ResourceLocation) gets called */
if (texture instanceof MultiResourceLocation && McLib.multiskinMultiThreaded.get())
{
MultiskinThread.add((MultiResourceLocation) texture);
return;
}
image = new CachedImage(ImageIO.read(Minecraft.getMinecraft().getResourceManager().getResource(texture).getInputStream()));
images.put(texture, image);
}
if (image.timer > 20)
{
image.timer = 20;
}
Chunk chunk = fillChunk(image.image, renderer);
if (chunk.stats > 0)
{
id = generateDisplayList(chunk, renderer);
}
}
catch (Exception e)
{
System.err.println("An error occurred during construction of extruded 3D layer for texture " + texture + " and limb " + renderer.limb.name);
e.printStackTrace();
}
map.put(texture, id);
}
/**
* Fill chunk based on given texture
*
* Basically, this method is responsible for filling the chunk data
* with outer voxels. The voxels are getting filled based on the
* limb's offset and Minecraft's cube mapping.
*
* There is a lot of copy-paste code since I'm not sure
*/
private static Chunk fillChunk(BufferedImage image, ModelCustomRenderer renderer)
{
final int threshold = 0x80;
/* Extrude factor */
int ef = renderer.model.model.extrudeMaxFactor;
int stepX = (int) (image.getWidth() / renderer.textureWidth);
int stepY = (int) (image.getHeight() / renderer.textureHeight);
int oStepX = stepX;
int oStepY = stepY;
if (ef > 1)
{
ef = Math.min(ef, Math.min(stepX, stepY));
if (stepX > 1) stepX = (int) (image.getWidth() / (renderer.textureWidth * ef));
if (stepY > 1) stepY = (int) (image.getHeight() / (renderer.textureHeight * ef));
}
/* Extrude Factor Inwards */
int efi = MathUtils.clamp(renderer.model.model.extrudeInwards, 1, ef);
int w = renderer.limb.size[0];
int h = renderer.limb.size[1];
int d = renderer.limb.size[2];
Chunk chunk = new Chunk(w, h, d, ef);
int offsetX = renderer.limb.texture[0];
int offsetY = renderer.limb.texture[1];
/* Top & bottom */
int x = (offsetX + d) * oStepX;
int y = offsetY * oStepY;
for (int i = 0; i < chunk.w; i++)
{
for (int j = 0; j < chunk.d; j++)
{
int alpha = image.getRGB(x + i * stepX, y + j * stepY) >> 24 & 0xff;
if (alpha >= threshold)
{
for (int k = 0; k < efi; k ++)
{
chunk.setBlockBit(i, chunk.h - 1 - k, j, TOP_BIT);
}
}
}
}
x = (offsetX + d + w) * oStepX;
y = offsetY * oStepY;
for (int i = 0; i < chunk.w; i++)
{
for (int j = 0; j < chunk.h; j++)
{
int alpha = image.getRGB(x + i * stepX, y + j * stepY) >> 24 & 0xff;
if (alpha >= threshold)
{
for (int k = 0; k < efi; k ++)
{
chunk.setBlockBit(i, k, j, BOTTOM_BIT);
}
}
}
}
/* Front & back */
x = (offsetX + d) * oStepX;
y = (offsetY + d) * oStepY;
for (int i = 0; i < chunk.w; i++)
{
for (int j = 0; j < chunk.h; j++)
{
int alpha = image.getRGB(x + i * stepX, y + j * stepY) >> 24 & 0xff;
if (alpha >= threshold)
{
for (int k = 0; k < efi; k ++)
{
chunk.setBlockBit(i, chunk.h - j - 1, chunk.d - 1 - k, FRONT_BIT);
}
}
}
}
x = (offsetX + d * 2 + w) * oStepX;
y = (offsetY + d) * oStepY;
for (int i = 0; i < chunk.w; i++)
{
for (int j = 0; j < chunk.h; j++)
{
int alpha = image.getRGB(x + i * stepX, y + j * stepY) >> 24 & 0xff;
if (alpha >= threshold)
{
for (int k = 0; k < efi; k ++)
{
chunk.setBlockBit(chunk.w - i - 1, chunk.h - j - 1, k, BACK_BIT);
}
}
}
}
/* Left & right */
x = offsetX * oStepX;
y = (offsetY + d) * oStepY;
for (int i = 0; i < chunk.d; i++)
{
for (int j = 0; j < chunk.h; j++)
{
int alpha = image.getRGB(x + i * stepX, y + j * stepY) >> 24 & 0xff;
if (alpha >= threshold)
{
for (int k = 0; k < efi; k ++)
{
chunk.setBlockBit(k, chunk.h - j - 1, i, LEFT_BIT);
}
}
}
}
x = (offsetX + d + w) * oStepX;
y = (offsetY + d) * oStepY;
for (int i = 0; i < chunk.d; i++)
{
for (int j = 0; j < chunk.h; j++)
{
int xx = x + i * stepX;
int yy = y + j * stepY;
int color = image.getRGB(xx, yy);
int alpha = color >> 24 & 0xff;
if (alpha >= threshold)
{
for (int k = 0; k < efi; k ++)
{
chunk.setBlockBit(chunk.w - 1 - k, chunk.h - j - 1, chunk.d - i - 1, RIGHT_BIT);
}
}
}
}
return chunk;
}
/**
* Generate display list out of chunk
*/
private static int generateDisplayList(Chunk chunk, ModelCustomRenderer renderer)
{
int id = GLAllocation.generateDisplayLists(1);
GlStateManager.glNewList(id, 4864);
generateGeometry(chunk, renderer);
GlStateManager.glEndList();
return id;
}
/**
* Generate geometry based on given chunk. This method is basically
* using stupid (instead of greedy) voxel meshing in order to
* compile the geometry.
*
* TODO: Fix UV mapping on non primary sides to match the edges (for high-res textures, primarily)
*/
private static void generateGeometry(Chunk chunk, ModelCustomRenderer renderer)
{
BufferBuilder buffer = Tessellator.getInstance().getBuffer();
int ef = chunk.ef;
int w = renderer.limb.size[0] * ef;
int h = renderer.limb.size[1] * ef;
int d = renderer.limb.size[2] * ef;
float f = 1F / 16F / ef;
float so = renderer.limb.sizeOffset * ef;
float tw = renderer.textureWidth * ef;
float th = renderer.textureHeight * ef;
int offsetX = renderer.limb.texture[0] * ef;
int offsetY = renderer.limb.texture[1] * ef;
boolean mirror = renderer.limb.mirror;
Offset off = new Offset(0, 0);
Offset offmax = new Offset(0, 0);
buffer.begin(GL11.GL_QUADS, VertexBuilder.getFormat(false, true, false, true));
for (int x = 0; x < chunk.w; x++)
{
for (int y = 0; y < chunk.h; y++)
{
for (int z = 0; z < chunk.d; z++)
{
int blockX = mirror ? w - x - 1 : x;
byte block = chunk.getBlock(blockX, y, z);
if (block == 0)
{
continue;
}
float sw = w + so * 2;
float sh = h + so * 2;
float sd = d + so * 2;
float aX = -renderer.limb.anchor[0] * sw + sw;
float aY = -renderer.limb.anchor[1] * sh + sh;
float aZ = -renderer.limb.anchor[2] * sd + sd;
/* Minimum and maximum */
float mnx = ((x + (mirror ? 1 : 0)) * (sw / (float) w) - aX) * f;
float mmx = ((x + (mirror ? 0 : 1)) * (sw / (float) w) - aX) * f;
float mny = -(y * (sh / (float) h) - aY) * f;
float mmy = -((y + 1) * (sh / (float) h) - aY) * f;
float mnz = -(z * (sd / (float) d) - aZ) * f;
float mmz = -((z + 1) * (sd / (float) d) - aZ) * f;
/* Top & Bottom */
if (!chunk.hasBlock(blockX, y + 1, z))
{
if (!calculateOffset(off, offmax, (byte) (block & TOP_BIT), offsetX, offsetY, w, h, d, blockX, y, z, tw, th))
{
calculateOffset(off, offmax, block, offsetX, offsetY, w, h, d, blockX, y, z, tw, th);
}
buffer.pos(mnx, mmy, mnz).tex(off.x, off.y).normal(0, -1, 0).endVertex();
buffer.pos(mnx, mmy, mmz).tex(off.x, offmax.y).normal(0, -1, 0).endVertex();
buffer.pos(mmx, mmy, mmz).tex(offmax.x, offmax.y).normal(0, -1, 0).endVertex();
buffer.pos(mmx, mmy, mnz).tex(offmax.x, off.y).normal(0, -1, 0).endVertex();
}
if (!chunk.hasBlock(blockX, y - 1, z))
{
if (!calculateOffset(off, offmax, (byte) (block & BOTTOM_BIT), offsetX, offsetY, w, h, d, blockX, y, z, tw, th))
{
calculateOffset(off, offmax, block, offsetX, offsetY, w, h, d, blockX, y, z, tw, th);
}
buffer.pos(mnx, mny, mnz).tex(off.x, off.y).normal(0, 1, 0).endVertex();
buffer.pos(mmx, mny, mnz).tex(offmax.x, off.y).normal(0, 1, 0).endVertex();
buffer.pos(mmx, mny, mmz).tex(offmax.x, offmax.y).normal(0, 1, 0).endVertex();
buffer.pos(mnx, mny, mmz).tex(off.x, offmax.y).normal(0, 1, 0).endVertex();
}
/* Front & back */
if (!chunk.hasBlock(blockX, y, z + 1))
{
if (!calculateOffset(off, offmax, (byte) (block & FRONT_BIT), offsetX, offsetY, w, h, d, blockX, y, z, tw, th))
{
calculateOffset(off, offmax, block, offsetX, offsetY, w, h, d, blockX, y, z, tw, th);
}
buffer.pos(mnx, mmy, mmz).tex(off.x, off.y).normal(0, 0, -1).endVertex();
buffer.pos(mnx, mny, mmz).tex(off.x, offmax.y).normal(0, 0, -1).endVertex();
buffer.pos(mmx, mny, mmz).tex(offmax.x, offmax.y).normal(0, 0, -1).endVertex();
buffer.pos(mmx, mmy, mmz).tex(offmax.x, off.y).normal(0, 0, -1).endVertex();
}
if (!chunk.hasBlock(blockX, y, z - 1))
{
if (!calculateOffset(off, offmax, (byte) (block & BACK_BIT), offsetX, offsetY, w, h, d, blockX, y, z, tw, th))
{
calculateOffset(off, offmax, block, offsetX, offsetY, w, h, d, blockX, y, z, tw, th);
}
buffer.pos(mnx, mmy, mnz).tex(offmax.x, off.y).normal(0, 0, 1).endVertex();
buffer.pos(mmx, mmy, mnz).tex(off.x, off.y).normal(0, 0, 1).endVertex();
buffer.pos(mmx, mny, mnz).tex(off.x, offmax.y).normal(0, 0, 1).endVertex();
buffer.pos(mnx, mny, mnz).tex(offmax.x, offmax.y).normal(0, 0, 1).endVertex();
}
/* Left & Right */
if (!chunk.hasBlock(blockX + 1, y, z))
{
if (!calculateOffset(off, offmax, (byte) (block & RIGHT_BIT), offsetX, offsetY, w, h, d, blockX, y, z, tw, th))
{
calculateOffset(off, offmax, block, offsetX, offsetY, w, h, d, blockX, y, z, tw, th);
}
buffer.pos(mmx, mmy, mnz).tex(offmax.x, off.y).normal(1, 0, 0).endVertex();
buffer.pos(mmx, mmy, mmz).tex(off.x, off.y).normal(1, 0, 0).endVertex();
buffer.pos(mmx, mny, mmz).tex(off.x, offmax.y).normal(1, 0, 0).endVertex();
buffer.pos(mmx, mny, mnz).tex(offmax.x, offmax.y).normal(1, 0, 0).endVertex();
}
if (!chunk.hasBlock(blockX - 1, y, z))
{
if (!calculateOffset(off, offmax, (byte) (block & LEFT_BIT), offsetX, offsetY, w, h, d, blockX, y, z, tw, th))
{
calculateOffset(off, offmax, block, offsetX, offsetY, w, h, d, blockX, y, z, tw, th);
}
buffer.pos(mnx, mmy, mnz).tex(off.x, off.y).normal(-1, 0, 0).endVertex();
buffer.pos(mnx, mny, mnz).tex(off.x, offmax.y).normal(-1, 0, 0).endVertex();
buffer.pos(mnx, mny, mmz).tex(offmax.x, offmax.y).normal(-1, 0, 0).endVertex();
buffer.pos(mnx, mmy, mmz).tex(offmax.x, off.y).normal(-1, 0, 0).endVertex();
}
}
}
}
Tessellator.getInstance().draw();
}
private static boolean calculateOffset(Offset offset, Offset max, byte block, int offsetX, int offsetY, int w, int h, int d, int x, int y, int z, float tw, float th)
{
/* Right */
float offX = -1;
float offY = -1;
/* Top */
if ((block & TOP_BIT) != 0)
{
offX = offsetX + d + x;
offY = offsetY + z;
}
/* Bottom */
else if ((block & BOTTOM_BIT) != 0)
{
offX = offsetX + d + w + x;
offY = offsetY + z;
}
/* Front */
else if ((block & FRONT_BIT) != 0)
{
offX = offsetX + d + x;
offY = offsetY + d + h - y - 1;
}
/* Back */
else if ((block & BACK_BIT) != 0)
{
offX = offsetX + d * 2 + w * 2 - x - 1;
offY = offsetY + d + h - y - 1;
}
/* Left */
else if ((block & LEFT_BIT) != 0)
{
offX = offsetX + z;
offY = offsetY + d + h - y - 1;
}
else if ((block & RIGHT_BIT) != 0)
{
offX = offsetX + d + w + d - z - 1;
offY = offsetY + d + h - y - 1;
}
if (offX == -1 && offY == -1)
{
return false;
}
float offMX = (offX + 1) / tw;
float offMY = (offY + 1) / th;
offX /= tw;
offY /= th;
offset.set(offX, offY);
max.set(offMX, offMY);
return true;
}
/**
* Clean everything
*/
public static void clear()
{
for (Map<ResourceLocation, Integer> map : layers.values())
{
for (Integer i : map.values())
{
if (i != -1)
{
GL11.glDeleteLists(i, 1);
}
}
}
layers.clear();
}
/**
* Clean up layers by texture
*/
public static void clearByTexture(ResourceLocation texture)
{
for (Map<ResourceLocation, Integer> map : layers.values())
{
if (map.containsKey(texture))
{
int i = map.remove(texture);
if (i != -1)
{
GL11.glDeleteLists(i, 1);
}
}
}
}
/**
* Clean up layers by model
*/
public static void clearByModel(ModelCustom model)
{
if (model == null)
{
return;
}
for (ModelCustomRenderer renderer : model.limbs)
{
if (!renderer.limb.is3D)
{
continue;
}
Map<ResourceLocation, Integer> map = layers.remove(renderer);
if (map == null)
{
continue;
}
for (Integer i : map.values())
{
GL11.glDeleteLists(i.intValue(), 1);
}
}
}
/**
* Cached image class
*/
public static class CachedImage
{
public BufferedImage image;
public int timer = 10;
public CachedImage(BufferedImage image)
{
this.image = image;
}
}
/**
* Chunk class
*
* Another class I extracted from my unfinished voxel video game.
* This class represents a voxel chunk.
*/
public static class Chunk
{
/**
* Array of block data
*/
protected byte[] data;
public final int w;
public final int h;
public final int d;
public int stats;
public int ef;
/**
* Initialize empty chunk data
*/
public Chunk(int w, int h, int d, int ef)
{
w *= ef;
h *= ef;
d *= ef;
this.w = w;
this.h = h;
this.d = d;
this.ef = ef;
this.data = new byte[w * h * d];
}
/**
* Set block at given coordinates
*/
public void setBlock(int x, int y, int z, byte block)
{
if (x < 0 || y < 0 || z < 0 || x >= this.w || y >= this.h || z >= this.d)
{
return;
}
byte old = this.data[x + y * this.w + z * this.w * this.h];
this.data[x + y * this.w + z * this.w * this.h] = block;
if (block != old)
{
this.stats += (block == 0) ? -1 : 1;
}
}
/**
* Set block at given coordinates
*/
public void setBlockBit(int x, int y, int z, byte bit)
{
if (x < 0 || y < 0 || z < 0 || x >= this.w || y >= this.h || z >= this.d)
{
return;
}
byte old = this.data[x + y * this.w + z * this.w * this.h];
byte block = (byte) (old | bit);
this.data[x + y * this.w + z * this.w * this.h] = block;
if (block != old)
{
this.stats += (block == 0) ? -1 : 1;
}
}
/**
* Is this chunk has a block at given coordinates
*/
public boolean hasBlock(int x, int y, int z)
{
return this.getBlock(x, y, z) != 0;
}
/**
* Get block at given coordinate
*/
public byte getBlock(int x, int y, int z)
{
if (x < 0 || y < 0 || z < 0 || x >= this.w || y >= this.h || z >= this.d)
{
return 0;
}
return this.data[x + y * this.w + z * this.w * this.h];
}
}
public static class Offset
{
public float x;
public float y;
public Offset(float x, float y)
{
this.set(x, y);
}
public void set(float x, float y)
{
this.x = x;
this.y = y;
}
}
} | 23,786 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
IModelCustom.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/parsing/IModelCustom.java | package mchorse.blockbuster.client.model.parsing;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
/**
* Custom model interface
*
* This interface is used as a trait for models that extend from
* {@link ModelCustom} for {@link ModelParser} to inject the
* {@link ModelCustomRenderer}s in the public fields of the instance.
*/
public interface IModelCustom
{
/**
* Gets called when the {@link ModelParser} has finished generating its
* limbs.
*/
public void onGenerated();
} | 573 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelExporter.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/parsing/ModelExporter.java | package mchorse.blockbuster.client.model.parsing;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.ModelUtils;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.PositionTextureVertex;
import net.minecraft.client.model.TextureOffset;
import net.minecraft.client.model.TexturedQuad;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.util.ResourceLocation;
/**
* Model exporter
*
* Model exporter class is responsible for exporting Minecraft in-game models
* based on the values of ModelBase ModelRenderer's ModelBoxes and given entity.
*/
public class ModelExporter
{
private EntityLivingBase entity;
private RenderLivingBase<EntityLivingBase> render;
private int limbId;
public ModelExporter(EntityLivingBase entity, RenderLivingBase<EntityLivingBase> render)
{
this.entity = entity;
this.render = render;
}
private ModelBase getModel()
{
return this.render.getMainModel();
}
/**
* Main method of this class.
*
* This method is responsible for exporting a JSON model based on the values
* of given renderer's model and entity state.
*
* See private methods for more information about this export process.
*/
public Model exportModel(String name)
{
Model data = new Model();
this.limbId = 0;
this.render.doRender(this.entity, 0, -420, 0, 0, 0);
ModelBase model = this.getModel();
this.setupProperties(data, model, name);
Map<String, ModelRenderer> limbs = this.generateLimbs(data, model);
/* Save standing, sleeping and flying poses */
this.render.doRender(this.entity, 0, -420, 0, 0, 0);
this.savePose("standing", data, limbs);
this.savePose("sleeping", data, limbs);
this.savePose("flying", data, limbs);
/* Save sneaking pose */
this.setSneaking(this.entity);
if (this.render.getMainModel() instanceof ModelBiped)
{
ModelBiped biped = ((ModelBiped) this.render.getMainModel());
boolean old = biped.isSneak;
biped.isSneak = true;
this.render.doRender(this.entity, 0, -420, 0, 0, 0);
biped.isSneak = old;
}
else
{
this.render.doRender(this.entity, 0, -420, 0, 0, 0);
}
this.savePose("sneaking", data, limbs);
this.setDefaultTexture(data);
return data;
}
public String exportJSON(String name)
{
return ModelUtils.toJson(this.exportModel(name));
}
/**
* Tries to set default texture
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private void setDefaultTexture(Model data)
{
Class<?> clazz = Render.class;
for (Method method : clazz.getDeclaredMethods())
{
Class[] args = method.getParameterTypes();
boolean hasEntityArg = args.length == 1 && args[0].isAssignableFrom(Entity.class);
boolean returnsRL = method.getReturnType().isAssignableFrom(ResourceLocation.class);
if (hasEntityArg && returnsRL)
{
try
{
method.setAccessible(true);
data.defaultTexture = (ResourceLocation) method.invoke(this.render, this.entity);
}
catch (Exception e)
{
e.printStackTrace();
}
break;
}
}
}
/**
* Set entity sneaking
*/
private void setSneaking(EntityLivingBase entity)
{
if (entity instanceof EntityTameable)
{
((EntityTameable) entity).setSitting(true);
}
else
{
entity.setSneaking(true);
}
}
/**
* Save pose transformations for every limb
*/
private void savePose(String poseName, Model data, Map<String, ModelRenderer> limbs)
{
ModelPose pose = new ModelPose();
/* Set size */
float width = this.entity.width;
float height = this.entity.height;
pose.size = new float[] {width, height, width};
/* Allocate transforms */
for (Map.Entry<String, ModelRenderer> entry : limbs.entrySet())
{
String key = entry.getKey();
ModelRenderer renderer = entry.getValue();
ModelTransform transform = new ModelTransform();
float PI = (float) Math.PI;
float rx = renderer.rotateAngleX * 180 / PI;
float ry = renderer.rotateAngleY * 180 / PI;
float rz = renderer.rotateAngleZ * 180 / PI;
float x = renderer.rotationPointX;
float y = renderer.rotationPointY;
float z = renderer.rotationPointZ;
if (data.limbs.get(key).parent.isEmpty())
{
x *= -1;
y = -(y - 24);
z *= -1;
}
else
{
x *= -1;
y *= -1;
z *= -1;
}
transform.rotate = new float[] {rx, ry, rz};
transform.translate = new float[] {x, y, z};
pose.limbs.put(key, transform);
}
data.poses.put(poseName, pose);
}
/**
* Setup main properties for given model
*/
private void setupProperties(Model data, ModelBase model, String name)
{
data.name = name;
data.texture = new int[] {model.textureWidth, model.textureHeight};
}
/**
* Generate limbs from the given model
*/
private Map<String, ModelRenderer> generateLimbs(Model data, ModelBase model)
{
Map<String, ModelRenderer> limbs = new HashMap<String, ModelRenderer>();
int width = 0;
int height = 0;
for (ModelRenderer renderer : this.getModelRenderers(model))
{
this.generateLimbs(limbs, renderer, data, model, "");
width = Math.max(width, (int) renderer.textureWidth);
height = Math.max(height, (int) renderer.textureHeight);
}
/* Some bastard decided that it was a smart idea to define two variables
* in Model's constructor and inject those values directly into the
* ModelRenderer via setTextureSize() instead of setting model's
* properties textureWidth and textureHeight. Therefore ModelBase
* properties has misleading result.
*
* This is a workaround to inject the right texture size for exporting
* JSON model. Basically, if the texture size from JSON model doesn't
* correspond with values that has been set from ModelRenderers,
* it uses the greater value that was got from ModelRenderers.
*
* Zero check for width and height is just in case.
*
* See ModelIronGolem for more information. I hope it wasn't jeb.
*/
if (data.texture[0] != width || data.texture[1] != height && width != 0 && height != 0)
{
data.texture = new int[] {width, height};
}
return limbs;
}
/**
* Recursive method for generating limbs
*/
private void generateLimbs(Map<String, ModelRenderer> limbs, ModelRenderer renderer, Model data, ModelBase model, String parentName)
{
int j = 0;
String firstName = "";
for (ModelBox box : renderer.cubeList)
{
ModelLimb limb = new ModelLimb();
String boxName = box.boxName != null ? box.boxName : "";
String name = boxName.isEmpty() ? "limb_" + this.limbId : boxName;
if (j == 0)
{
limb.mirror = renderer.mirror;
limb.parent = parentName;
firstName = name;
limbs.put(name, renderer);
}
else
{
limb.parent = firstName;
}
limb.size = this.getModelSize(box);
limb.texture = this.getModelOffset(box, renderer, model);
limb.anchor = this.getAnchor(box, limb.size);
data.limbs.put(name, limb);
this.limbId++;
j++;
}
if (renderer.childModels == null)
{
return;
}
for (ModelRenderer child : renderer.childModels)
{
this.generateLimbs(limbs, child, data, model, firstName);
}
}
/**
* Compute model size based on the box in the model renderer
*/
private int[] getModelSize(ModelBox box)
{
int w = (int) (box.posX2 - box.posX1);
int h = (int) (box.posY2 - box.posY1);
int d = (int) (box.posZ2 - box.posZ1);
return new int[] {w, h, d};
}
/**
* Get texture offset of the model based on its box
*/
private int[] getModelOffset(ModelBox box, ModelRenderer renderer, ModelBase model)
{
TextureOffset offset = model.getTextureOffset(box.boxName);
if (offset != null)
{
return new int[] {offset.textureOffsetX, offset.textureOffsetY};
}
int[] zero = new int[] {0, 0};
Field field = this.getFieldByType(TexturedQuad[].class, ModelBox.class);
TexturedQuad[] quads;
field.setAccessible(true);
try
{
quads = (TexturedQuad[]) field.get(box);
}
catch (Exception e)
{
e.printStackTrace();
return zero;
}
/* Getting the minimum */
float minX = 1.0F;
float minY = 1.0F;
for (TexturedQuad quad : quads)
{
for (PositionTextureVertex vertex : quad.vertexPositions)
{
minX = Math.min(vertex.texturePositionX, minX);
minY = Math.min(vertex.texturePositionY, minY);
}
}
minX *= renderer.textureWidth;
minY *= renderer.textureHeight;
return new int[] {(int) minX, (int) minY};
}
/**
* Compute anchor based on the renderer
*/
private float[] getAnchor(ModelBox box, int[] size)
{
float w = size[0] != 0 ? -box.posX1 / size[0] : 0;
float h = size[1] != 0 ? -box.posY1 / size[1] : 0;
float d = size[2] != 0 ? -box.posZ1 / size[2] : 0;
return new float[] {w, h, d};
}
/**
* Get all model renderers that given model has (even if that is an array
* of ModelRenderers)
*/
private List<ModelRenderer> getModelRenderers(ModelBase model)
{
List<ModelRenderer> renderers = new ArrayList<ModelRenderer>();
Class<?> rClass = ModelRenderer.class;
Class<?> aRClass = ModelRenderer[].class;
for (Field field : getInheritedFields(model.getClass()))
{
Class<?> type = field.getType();
if (!type.isAssignableFrom(rClass) && !type.isAssignableFrom(aRClass)) continue;
if (!field.isAccessible()) field.setAccessible(true);
try
{
if (type.isAssignableFrom(rClass))
{
ModelRenderer renderer = (ModelRenderer) field.get(model);
if (renderer != null && renderers.indexOf(renderer) == -1)
{
renderers.add(renderer);
}
}
else if (type.isAssignableFrom(aRClass))
{
ModelRenderer[] moreRenderers = (ModelRenderer[]) field.get(model);
for (ModelRenderer renderer : moreRenderers)
{
if (renderer != null && renderers.indexOf(renderer) == -1)
{
renderers.add(renderer);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
continue;
}
}
/* Eliminate any children model renderers */
List<ModelRenderer> roots = new ArrayList<ModelRenderer>();
for (ModelRenderer child : renderers)
{
boolean isChild = false;
for (ModelRenderer parent : renderers)
{
if (parent.childModels != null && parent.childModels.contains(child))
{
isChild = true;
break;
}
}
if (!isChild)
{
roots.add(child);
}
}
return roots;
}
/**
* Get first field that corresponds to given class type in given class
* subject
*/
private Field getFieldByType(Class<?> type, Class<?> subject)
{
for (Field field : subject.getDeclaredFields())
{
if (field.getType().equals(type)) return field;
}
return null;
}
/**
* From StackOverflow
*/
public static List<Field> getInheritedFields(Class<?> type)
{
List<Field> fields = new ArrayList<Field>();
for (Class<?> c = type; c != null; c = c.getSuperclass())
{
fields.addAll(Arrays.asList(c.getDeclaredFields()));
}
return fields;
}
} | 14,090 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ModelParser.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/model/parsing/ModelParser.java | package mchorse.blockbuster.client.model.parsing;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.ModelLimb;
import mchorse.blockbuster.api.ModelLimb.ArmorSlot;
import mchorse.blockbuster.api.ModelLimb.Holding;
import mchorse.blockbuster.api.ModelPose;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.api.formats.IMeshes;
import mchorse.blockbuster.client.model.ModelCustom;
import mchorse.blockbuster.client.model.ModelCustomRenderer;
import mchorse.metamorph.Metamorph;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Model parser
*
* This class is responsible for converting models into in-game renderable
* models (ModelCustom)
*/
@SideOnly(Side.CLIENT)
public class ModelParser
{
public String key;
public Map<String, IMeshes> meshes;
/**
* Parse with default class
*/
public static ModelCustom parse(String key, Model data)
{
return parse(key, data, ModelCustom.class, null);
}
/**
* Parse with default class
*/
public static ModelCustom parse(String key, Model data, Map<String, IMeshes> meshes)
{
return parse(key, data, ModelCustom.class, meshes);
}
/**
* Parse given input stream as JSON model, and then save this model in
* the custom model repository
*/
public static ModelCustom parse(String key, Model data, Class<? extends ModelCustom> clazz, Map<String, IMeshes> meshes)
{
try
{
return new ModelParser(key, meshes).parseModel(data, clazz);
}
catch (Exception e)
{
System.out.println("Model for key '" + key + "' couldn't converted to ModelCustom!");
e.printStackTrace();
}
return null;
}
public ModelParser(String key, Map<String, IMeshes> meshes)
{
if (meshes == null)
{
meshes = new HashMap<String, IMeshes>();
}
this.key = key;
this.meshes = meshes;
}
/**
* Parse and build model out of given JSON string. Throws exception in case
* if parsed model doesn't have at least one required pose.
*/
public ModelCustom parseModel(Model data, Class<? extends ModelCustom> clazz) throws Exception
{
ModelCustom model = clazz.getConstructor(Model.class).newInstance(data);
this.generateLimbs(data, model);
if (model instanceof IModelCustom)
{
((IModelCustom) model).onGenerated();
}
return model;
}
/**
* Generate limbs for a custom model renderer based on a passed model data
* which was parsed from JSON.
*/
protected void generateLimbs(Model data, ModelCustom model)
{
/* Define lists for different purposes */
Map<String, ModelCustomRenderer> limbs = new HashMap<String, ModelCustomRenderer>();
List<ModelRenderer> renderable = new ArrayList<ModelRenderer>();
List<ModelRenderer> left = new ArrayList<ModelRenderer>();
List<ModelRenderer> right = new ArrayList<ModelRenderer>();
List<ModelRenderer> armor = new ArrayList<ModelRenderer>();
ModelPose standing = data.poses.get("standing");
/* First, iterate to create every limb */
for (Map.Entry<String, ModelLimb> entry : data.limbs.entrySet())
{
ModelLimb limb = entry.getValue();
ModelTransform transform = standing.limbs.get(entry.getKey());
ModelCustomRenderer renderer = this.createRenderer(model, data, limb, transform);
if (limb.holding == Holding.LEFT) left.add(renderer);
if (limb.holding == Holding.RIGHT) right.add(renderer);
if (limb.slot != ArmorSlot.NONE) armor.add(renderer);
limbs.put(entry.getKey(), renderer);
}
/* Then, iterate to attach child to their parents */
for (Map.Entry<String, ModelCustomRenderer> entry : limbs.entrySet())
{
ModelLimb limb = data.limbs.get(entry.getKey());
if (!limb.parent.isEmpty())
{
limbs.get(limb.parent).addChild(entry.getValue());
}
else
{
renderable.add(entry.getValue());
}
/* Inject ModelCustomRenderers into the model's fields */
if (model instanceof IModelCustom)
{
try
{
Field field = model.getClass().getField(entry.getKey());
if (field != null)
{
field.set(model, entry.getValue());
}
}
catch (Exception e)
{
Metamorph.log("Field '" + entry.getKey() + "' was not found or is not accessible for " + model.getClass().getSimpleName());
}
}
}
/* Assign values */
model.left = left.toArray(new ModelCustomRenderer[left.size()]);
model.right = right.toArray(new ModelCustomRenderer[right.size()]);
model.armor = armor.toArray(new ModelCustomRenderer[armor.size()]);
model.limbs = limbs.values().toArray(new ModelCustomRenderer[limbs.size()]);
model.renderable = renderable.toArray(new ModelCustomRenderer[renderable.size()]);
}
/**
* Create limb renderer for the model
*/
protected ModelCustomRenderer createRenderer(ModelCustom model, Model data, ModelLimb limb, ModelTransform transform)
{
ModelCustomRenderer renderer = null;
float w = limb.size[0];
float h = limb.size[1];
float d = limb.size[2];
float ax = 1 - limb.anchor[0];
float ay = limb.anchor[1];
float az = limb.anchor[2];
IMeshes meshes = this.meshes.get(limb.name);
if (meshes != null)
{
renderer = meshes.createRenderer(data, model, limb, transform);
}
if (renderer == null)
{
renderer = new ModelCustomRenderer(model, limb, transform);
renderer.mirror = limb.mirror;
renderer.addBox(-ax * w, -ay * h, -az * d, (int) w, (int) h, (int) d, limb.sizeOffset);
}
renderer.applyTransform(transform);
return renderer;
}
} | 6,590 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
EntityTransformationUtils.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/utils/EntityTransformationUtils.java | package mchorse.blockbuster.utils;
import net.minecraft.entity.Entity;
/**
* This is a utils class to avoid reflection to get asm injected variables of entity class.
*/
public class EntityTransformationUtils
{
/* LEAVE THE RETURN TYPES 0 or the core asm transformation will fail!*/
public static double getPrevPrevPosX(Entity entity)
{
return 0;
}
public static double getPrevPrevPosY(Entity entity)
{
return 0;
}
public static double getPrevPrevPosZ(Entity entity)
{
return 0;
}
}
| 554 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.