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
ServerHandlerPlaybackButton.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/ServerHandlerPlaybackButton.java
package mchorse.blockbuster.network.server; import mchorse.blockbuster.common.item.ItemPlayback; import mchorse.blockbuster.network.common.PacketPlaybackButton; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class ServerHandlerPlaybackButton extends ServerMessageHandler<PacketPlaybackButton> { @Override public void run(EntityPlayerMP player, PacketPlaybackButton message) { if (!OpHelper.isPlayerOp(player)) { return; } ItemStack stack = player.getHeldItemMainhand(); if (!(stack.getItem() instanceof ItemPlayback)) { stack = player.getHeldItemOffhand(); } if (!(stack.getItem() instanceof ItemPlayback)) { return; } NBTTagCompound compound = stack.getTagCompound(); if (compound == null) { compound = new NBTTagCompound(); stack.setTagCompound(compound); } compound.removeTag("CameraPlay"); compound.removeTag("CameraProfile"); compound.removeTag("Scene"); if (message.location.isScene()) { compound.setString("Scene", message.location.getFilename()); } if (message.mode == 1) { compound.setBoolean("CameraPlay", true); } else if (message.mode == 2) { compound.setString("CameraProfile", message.profile); } } }
1,622
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerModifyModelBlock.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/ServerHandlerModifyModelBlock.java
package mchorse.blockbuster.network.server; 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.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; public class ServerHandlerModifyModelBlock extends ServerMessageHandler<PacketModifyModelBlock> { @Override public void run(EntityPlayerMP player, PacketModifyModelBlock message) { if (!OpHelper.isPlayerOp(player)) { return; } BlockPos pos = message.pos; TileEntity tile = this.getTE(player, pos); if (tile instanceof TileEntityModel) { ((TileEntityModel) tile).copyData(message.model, false); //set the blockstate in the world - important for servers tile.getWorld().setBlockState(message.pos, tile.getWorld().getBlockState(message.pos).withProperty(BlockModel.LIGHT, message.model.getSettings().getLightValue()) , 2); Dispatcher.DISPATCHER.get().sendToDimension(message, player.dimension); } } }
1,412
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerSceneManage.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerSceneManage.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.commands.CommandRecord; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.scene.PacketSceneManage; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.data.Record; import mchorse.blockbuster.recording.scene.Replay; import mchorse.blockbuster.recording.scene.Scene; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.client.Minecraft; import net.minecraft.command.CommandException; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.common.DimensionManager; import java.io.IOException; public class ServerHandlerSceneManage extends ServerMessageHandler<PacketSceneManage> { @Override public void run(EntityPlayerMP player, PacketSceneManage message) { if (!OpHelper.isPlayerOp(player)) { return; } if (message.action == PacketSceneManage.RENAME && CommonProxy.scenes.rename(message.source, message.destination)) { Dispatcher.sendTo(message, player); } else if (message.action == PacketSceneManage.REMOVE && CommonProxy.scenes.remove(message.source)) { Dispatcher.sendTo(message, player); } else if (message.action == PacketSceneManage.DUPE) { Scene source = CommonProxy.scenes.get(message.source, player.getEntityWorld()); Scene destinationDummy = new Scene(); destinationDummy.copy(source); destinationDummy.setId(message.destination); destinationDummy.setupIds(); destinationDummy.renamePrefix(source.getId(), destinationDummy.getId(), (id) -> id + "_copy"); for(int i = 0; i<destinationDummy.replays.size(); i++) { Replay replaySource = source.replays.get(i); Replay replayDestination = destinationDummy.replays.get(i); int counter = 0; try { Record record = CommandRecord.getRecord(replaySource.id).clone(); if (RecordUtils.isReplayExists(replayDestination.id)) { continue; } /* This could potentially cause renaming problems like _1_2_3_4 indexes while(RecordUtils.isReplayExists(replayDestination.id + ((counter != 0) ? "_"+Integer.toString(counter) : ""))) { counter++; }*/ record.filename = replayDestination.id + ((counter != 0) ? "_"+Integer.toString(counter) : ""); replayDestination.id = record.filename; record.save(RecordUtils.replayFile(record.filename)); CommonProxy.manager.records.put(record.filename, record); } catch (Exception e) { e.printStackTrace(); } } Dispatcher.sendTo(message, player); } } }
3,228
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerSceneRequestCast.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerSceneRequestCast.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.scene.PacketSceneCast; import mchorse.blockbuster.network.common.scene.PacketSceneRequestCast; import mchorse.blockbuster.recording.scene.Scene; import mchorse.blockbuster.recording.scene.SceneLocation; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; /** * This handler is used to force request of the cast by the director. */ public class ServerHandlerSceneRequestCast extends ServerMessageHandler<PacketSceneRequestCast> { @Override public void run(EntityPlayerMP player, PacketSceneRequestCast message) { if (!OpHelper.isPlayerOp(player) || message.location.isEmpty()) { return; } try { Scene scene = CommonProxy.scenes.load(message.location.getFilename()); Dispatcher.sendTo(new PacketSceneCast(new SceneLocation(scene)), player); } catch (Exception e) { e.printStackTrace(); } } }
1,197
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerScenePlayback.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerScenePlayback.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.common.scene.PacketScenePlayback; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerScenePlayback extends ServerMessageHandler<PacketScenePlayback> { @Override public void run(EntityPlayerMP player, PacketScenePlayback message) { if (!OpHelper.isPlayerOp(player) || message.location.isEmpty()) { return; } CommonProxy.scenes.toggle(message.location.getFilename(), player.world); } }
685
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerScenePause.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerScenePause.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.common.scene.PacketScenePause; import mchorse.blockbuster.recording.scene.Scene; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerScenePause extends ServerMessageHandler<PacketScenePause> { @Override public void run(EntityPlayerMP player, PacketScenePause message) { if (!OpHelper.isPlayerOp(player)) { return; } if (CommonProxy.manager.recorders.containsKey(player)) { if (CommonProxy.manager.cancel(player)) { Blockbuster.l10n.info(player, "action.cancel"); } } else { Scene scene = message.get(player.world); if (!scene.isPlaying()) { scene.resume(-1); } else { scene.pause(); } } } }
1,140
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerSceneCast.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerSceneCast.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.capabilities.recording.Recording; import mchorse.blockbuster.network.common.scene.PacketSceneCast; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerSceneCast extends ServerMessageHandler<PacketSceneCast> { @Override public void run(EntityPlayerMP player, PacketSceneCast message) { if (!OpHelper.isPlayerOp(player) || message.location.isEmpty()) { return; } try { CommonProxy.scenes.save(message.location.getFilename(), message.location.getScene()); Recording.get(player).setLastScene(message.location.getFilename()); } catch (Exception e) { e.printStackTrace(); } } }
940
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerRequestScenes.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerRequestScenes.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.scene.PacketRequestScenes; import mchorse.blockbuster.network.common.scene.PacketScenes; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerRequestScenes extends ServerMessageHandler<PacketRequestScenes> { @Override public void run(EntityPlayerMP player, PacketRequestScenes message) { if (!OpHelper.isPlayerOp(player)) { return; } Dispatcher.sendTo(new PacketScenes(CommonProxy.scenes.sceneFiles()), player); } }
769
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerSceneRecord.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/ServerHandlerSceneRecord.java
package mchorse.blockbuster.network.server.scene; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.common.scene.PacketSceneRecord; import mchorse.blockbuster.recording.data.Mode; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerSceneRecord extends ServerMessageHandler<PacketSceneRecord> { @Override public void run(EntityPlayerMP player, PacketSceneRecord message) { if (!OpHelper.isPlayerOp(player)) { return; } if (message.location.isScene()) { CommonProxy.scenes.record(message.location.getFilename(), message.record, message.offset, player); } else { CommonProxy.manager.record(message.record, player, Mode.ACTIONS, true, true, message.offset, null); } } }
930
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerScenePlay.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/sync/ServerHandlerScenePlay.java
package mchorse.blockbuster.network.server.scene.sync; import mchorse.blockbuster.network.common.scene.sync.PacketScenePlay; import mchorse.blockbuster.recording.scene.Scene; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerScenePlay extends ServerMessageHandler<PacketScenePlay> { @Override public void run(EntityPlayerMP player, PacketScenePlay message) { if (!OpHelper.isPlayerOp(player)) { return; } Scene scene = message.get(player.world); if (message.isPlay()) { if (!scene.playing) { scene.spawn(message.tick); } scene.resume(message.tick); } else if (message.isStop()) { scene.stopPlayback(true); } else if (message.isPause()) { scene.pause(); } else if (message.isStart()) { scene.spawn(message.tick); } else if (message.isRestart()) { scene.reload(message.tick); } } }
1,191
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerSceneGoto.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/scene/sync/ServerHandlerSceneGoto.java
package mchorse.blockbuster.network.server.scene.sync; import mchorse.blockbuster.network.common.scene.sync.PacketSceneGoto; import mchorse.blockbuster.recording.scene.Scene; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerSceneGoto extends ServerMessageHandler<PacketSceneGoto> { @Override public void run(EntityPlayerMP player, PacketSceneGoto message) { if (!OpHelper.isPlayerOp(player)) { return; } Scene scene = message.get(player.world); if (scene != null) { scene.goTo(message.tick, message.actions); } } }
730
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerGunInteract.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/gun/ServerHandlerGunInteract.java
package mchorse.blockbuster.network.server.gun; import mchorse.blockbuster.common.GunProps; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.blockbuster.common.item.ItemGun; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.guns.PacketGunInteract; import mchorse.blockbuster.utils.NBTUtils; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; /** * \* User: Evanechecssss * \* https://evanechecssss.github.io * \ */ public class ServerHandlerGunInteract extends ServerMessageHandler<PacketGunInteract> { @Override public void run(EntityPlayerMP player, PacketGunInteract packet) { interactWithGun(player, player.world.getEntityByID(packet.id), packet.stack); } public static void interactWithGun(EntityPlayerMP player, Entity entity, ItemStack stack) { if (!(stack.getItem() instanceof ItemGun)) { return; } ItemGun gun = (ItemGun) stack.getItem(); GunProps props = NBTUtils.getGunProps(stack); if (props == null) { return; } EntityPlayer entityPlayer = entity instanceof EntityPlayer ? (EntityPlayer) entity : ((EntityActor) entity).fakePlayer; if (props.state == ItemGun.GunState.READY_TO_SHOOT && (entity instanceof EntityActor || props.storedShotDelay == 0)) { if (player != null) { Dispatcher.sendTo(new PacketGunInteract(stack, entity.getEntityId()), player); } gun.shootIt(stack, entityPlayer, entityPlayer.world); } } }
1,790
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerZoomCommand.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/gun/ServerHandlerZoomCommand.java
package mchorse.blockbuster.network.server.gun; import mchorse.blockbuster.common.GunProps; import mchorse.blockbuster.common.item.ItemGun; import mchorse.blockbuster.network.common.guns.PacketZoomCommand; import mchorse.blockbuster.utils.NBTUtils; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; /** * \* User: Evanechecssss * \* https://evanechecssss.github.io * \ */ public class ServerHandlerZoomCommand extends ServerMessageHandler<PacketZoomCommand> { @Override public void run(EntityPlayerMP player, PacketZoomCommand message) { if (!(player.getHeldItemMainhand().getItem() instanceof ItemGun)) { return; } Entity entity = player.world.getEntityByID(message.entity); GunProps props = NBTUtils.getGunProps(player.getHeldItemMainhand()); if (props == null || !(entity instanceof EntityPlayer)) { return; } if (message.zoomOn) { if (!props.zoomOnCommand.isEmpty()) { player.getServer().commandManager.executeCommand(player, props.zoomOnCommand); } } else { if (!props.zoomOffCommand.isEmpty()) { player.getServer().commandManager.executeCommand(player, props.zoomOffCommand); } } } }
1,491
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerGunReloading.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/gun/ServerHandlerGunReloading.java
package mchorse.blockbuster.network.server.gun; import mchorse.blockbuster.common.item.ItemGun; import mchorse.blockbuster.network.common.guns.PacketGunReloading; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; /** * \* User: Evanechecssss * \* https://evanechecssss.github.io * \ */ public class ServerHandlerGunReloading extends ServerMessageHandler<PacketGunReloading> { @Override public void run(EntityPlayerMP entityPlayerMP, PacketGunReloading packet) { ItemStack item = entityPlayerMP.getHeldItemMainhand(); if (item.getItem() instanceof ItemGun) { ItemGun gun = (ItemGun) item.getItem(); gun.reload(entityPlayerMP, item); } } }
814
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerGunInfo.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/gun/ServerHandlerGunInfo.java
package mchorse.blockbuster.network.server.gun; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.guns.PacketGunInfo; import mchorse.blockbuster.utils.NBTUtils; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; public class ServerHandlerGunInfo extends ServerMessageHandler<PacketGunInfo> { @Override public void run(EntityPlayerMP player, PacketGunInfo message) { if (!OpHelper.isPlayerOp(player)) { return; } ItemStack stack = player.getHeldItemMainhand(); if (NBTUtils.saveGunProps(stack, message.tag)) { IMessage packet = new PacketGunInfo(message.tag, player.getEntityId()); Dispatcher.sendTo(packet, player); Dispatcher.sendToTracked(player, packet); } } }
1,025
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerFramesOverwrite.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/ServerHandlerFramesOverwrite.java
package mchorse.blockbuster.network.server.recording; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.recording.PacketFramesOverwrite; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.data.Frame; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.client.gui.utils.keys.IKey; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.network.mclib.client.ClientHandlerAnswer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; public class ServerHandlerFramesOverwrite extends ServerMessageHandler<PacketFramesOverwrite> { /** * In case many people on a server want to overwrite the same record - avoid collision with packets. * The key identifies which record should have which ticks overwritten. * TODO If two people at the same time want to override the same ticks, this may be a problem. */ private static Map<OverwriteIdentifier, List<Frame>> overwriteQueue = new HashMap<>(); @Override public void run(EntityPlayerMP entityPlayerMP, PacketFramesOverwrite packet) { Record targetRecord; IKey answer = null; boolean status = false; if (packet.frames.isEmpty()) { System.out.println("Received an empty chunk..."); return; } try { targetRecord = CommonProxy.manager.get(packet.filename); if (targetRecord == null) { this.sendAnswer(packet, entityPlayerMP, IKey.format("blockbuster.error.recording.not_found", packet.filename), false); return; } } catch (Exception e) { this.sendAnswer(packet, entityPlayerMP, IKey.lang("blockbuster.gui.director.rotation_filter.record_save_error"), false); return; } OverwriteIdentifier key = null; /* * the constructor sorts from and to tick already. * It is important that from tick is always smaller than to tick, no matter what the client sends! */ OverwriteIdentifier targetKey = new OverwriteIdentifier(packet.getFrom(), packet.getTo(), packet.filename); for (Map.Entry<OverwriteIdentifier, List<Frame>> entry : overwriteQueue.entrySet()) { if (entry.getKey().equals(targetKey)) { key = entry.getKey(); break; } } if (key == null) { key = targetKey; overwriteQueue.put(key, new ArrayList<>()); } List<Frame> frames = overwriteQueue.get(key); if (this.insertChunk(packet.frames, packet.getIndex(), frames)) { if (frames.size() == (key.toTick - key.fromTick) + 1 && !frames.contains(null)) { if (key.toTick >= targetRecord.frames.size()) { status = false; answer = IKey.lang("blockbuster.gui.director.rotation_filter.record_save_error"); System.out.println("toTick " + key.toTick + " out of range of record frames size."); } else { for (int i = key.fromTick; i <= key.toTick; i++) { targetRecord.frames.set(i, frames.get(i - key.fromTick)); } try { RecordUtils.saveRecord(targetRecord); status = true; answer = IKey.lang("blockbuster.gui.director.rotation_filter.success"); } catch (IOException e) { status = false; answer = IKey.lang("blockbuster.gui.director.rotation_filter.record_save_error"); e.printStackTrace(); } } overwriteQueue.remove(key); } } else { status = false; answer = IKey.lang("blockbuster.gui.director.rotation_filter.frame_chunk_error"); overwriteQueue.remove(key); } if (answer != null) { this.sendAnswer(packet, entityPlayerMP, answer, status); } } private void sendAnswer(PacketFramesOverwrite packet, EntityPlayerMP player, IKey message, boolean status) { if (packet.getCallbackID().isPresent()) { ClientHandlerAnswer.sendAnswerTo(player, packet.getAnswer(new AbstractMap.SimpleEntry<>(message, status))); } } @SideOnly(Side.CLIENT) public static void sendFramesToServer(String filename, List<Frame> frames, int from, int to) { sendFramesToServer(filename, frames, from, to, null); } /** * * @param filename * @param frames * @param from * @param to * @param callback the callback that should be called when the answer from the server returns */ @SideOnly(Side.CLIENT) public static void sendFramesToServer(String filename, List<Frame> frames, int from, int to, @Nullable Consumer<AbstractMap.SimpleEntry<IKey, Boolean>> callback) { int cap = 400; if (frames.size() <= cap) { if (callback != null) { ClientHandlerAnswer.requestServerAnswer(Dispatcher.DISPATCHER, new PacketFramesOverwrite(from, to, 0, filename, frames), callback); } else { Dispatcher.sendToServer(new PacketFramesOverwrite(from, to, 0, filename, frames)); } return; } List<Frame> chunk = new ArrayList<>(); int chunkStart = 0; for (int i = 0; i < frames.size(); i++) { chunk.add(frames.get(i)); if (chunk.size() == cap || i == frames.size() - 1) { if (callback != null) { ClientHandlerAnswer.requestServerAnswer(Dispatcher.DISPATCHER, new PacketFramesOverwrite(from, to, chunkStart, filename, chunk), callback); } else { Dispatcher.sendToServer(new PacketFramesOverwrite(from, to, chunkStart, filename, chunk)); } chunk.clear(); chunkStart += cap; } } } protected boolean insertChunk(List<Frame> chunk, int targetIndex, List<Frame> frames) { /* * in case packets got shuffled on the way to the server, * check how to insert the chunk properly */ if (targetIndex > frames.size()) { Frame[] nulls = new Frame[targetIndex - frames.size()]; frames.addAll(Arrays.asList(nulls)); frames.addAll(chunk); } else if (targetIndex == frames.size()) { frames.addAll(chunk); } else { int i = targetIndex; while (i < frames.size() && i < targetIndex + chunk.size()) { if (frames.get(i) != null) { break; } i++; } /* if the part in frames only contains nulls insert chunk */ if (i == targetIndex + chunk.size()) { for (int j = targetIndex; j < targetIndex + chunk.size(); j++) { frames.set(j, chunk.get(j - targetIndex)); } } else { /* the chunk doesn't fit in the slot because there are non null values */ return false; } } return true; } /** * Identifier which record should get the specified ticks overwritten. */ private static class OverwriteIdentifier { /** * From tick to overwrite */ private int fromTick; /** * To tick (inclusive) to overwrite to */ private int toTick; private String filename; /** * Sorts from and to * @param from * @param to * @param filename */ public OverwriteIdentifier(int from, int to, String filename) { this.fromTick = Math.min(from, to); this.toTick = Math.max(from, to); this.filename = filename; } @Override public boolean equals(Object obj) { if (obj instanceof OverwriteIdentifier) { OverwriteIdentifier framesOverwrite = (OverwriteIdentifier) obj; return framesOverwrite.filename.equals(this.filename) && framesOverwrite.fromTick == this.fromTick && framesOverwrite.toTick == this.toTick; } return false; } } }
9,524
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerFramesChunk.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/ServerHandlerFramesChunk.java
package mchorse.blockbuster.network.server.recording; import java.io.IOException; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.capabilities.recording.Recording; import mchorse.blockbuster.network.common.recording.PacketFramesChunk; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.data.FrameChunk; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerFramesChunk extends ServerMessageHandler<PacketFramesChunk> { @Override public void run(EntityPlayerMP player, PacketFramesChunk message) { Record serverRecord = CommonProxy.manager.records.get(message.filename); FrameChunk chunk = CommonProxy.manager.chunks.get(message.filename); if (serverRecord == null) { return; } if (chunk == null) { chunk = new FrameChunk(message.count, message.offset); CommonProxy.manager.chunks.put(message.filename, chunk); } chunk.add(message.index, message.frames); if (chunk.isFilled()) { try { Recording.get(player).addRecording(message.filename, System.currentTimeMillis()); serverRecord.frames = chunk.compile(serverRecord.frames); serverRecord.save(RecordUtils.replayFile(message.filename)); serverRecord.fillMissingActions(); CommonProxy.manager.chunks.remove(message.filename); } catch (IOException e) { e.printStackTrace(); } } } }
1,732
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerRequestRecording.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/ServerHandlerRequestRecording.java
package mchorse.blockbuster.network.server.recording; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.client.recording.ClientHandlerFramesLoad; import mchorse.blockbuster.network.common.recording.PacketRequestRecording; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.function.Consumer; public class ServerHandlerRequestRecording extends ServerMessageHandler<PacketRequestRecording> { @Override public void run(EntityPlayerMP player, PacketRequestRecording message) { if (message.getCallbackID().isPresent()) { RecordUtils.sendRecordTo(message.getFilename(), player, message.getCallbackID().get()); } else { RecordUtils.sendRecordTo(message.getFilename(), player); } } /** * Request recording from server * @param filename * @param consumer the consumer that should be executed after the server has sent its answer */ @SideOnly(Side.CLIENT) public static void requestRecording(String filename, @Nullable Consumer<Record> consumer) { if (consumer != null) { int id = ClientHandlerFramesLoad.registerConsumer(consumer); Dispatcher.sendToServer(new PacketRequestRecording(filename, id)); } else { Dispatcher.sendToServer(new PacketRequestRecording(filename)); } } /** * Request recording from server * @param filename */ @SideOnly(Side.CLIENT) public static void requestRecording(String filename) { requestRecording(filename, null); } }
1,931
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerPlayback.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/ServerHandlerPlayback.java
package mchorse.blockbuster.network.server.recording; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.blockbuster.network.common.recording.PacketPlayback; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerPlayback extends ServerMessageHandler<PacketPlayback> { @Override public void run(EntityPlayerMP player, PacketPlayback message) { EntityActor actor = (EntityActor) player.world.getEntityByID(message.id); if (actor.playback != null) { actor.playback.playing = message.state; } } }
648
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerRequestFrames.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/ServerHandlerRequestFrames.java
package mchorse.blockbuster.network.server.recording; import mchorse.blockbuster.network.common.recording.PacketRequestFrames; import mchorse.blockbuster.recording.RecordUtils; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerRequestFrames extends ServerMessageHandler<PacketRequestFrames> { @Override public void run(EntityPlayerMP player, PacketRequestFrames message) { RecordUtils.sendRequestedRecord(message.id, message.filename, player); } }
551
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerUpdatePlayerData.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/ServerHandlerUpdatePlayerData.java
package mchorse.blockbuster.network.server.recording; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.common.recording.PacketUpdatePlayerData; import mchorse.blockbuster.recording.MPMHelper; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; public class ServerHandlerUpdatePlayerData extends ServerMessageHandler<PacketUpdatePlayerData> { @Override public void run(EntityPlayerMP player, PacketUpdatePlayerData message) { if (!OpHelper.isPlayerOp(player)) { return; } Record record = null; try { record = CommonProxy.manager.get(message.record); } catch (Exception e) {} if (record == null) { Blockbuster.l10n.error(player, "record.not_exist", message.record); return; } NBTTagCompound tag = new NBTTagCompound(); player.writeEntityToNBT(tag); record.playerData = tag; if (MPMHelper.isLoaded()) { tag = MPMHelper.getMPMData(player); if (tag != null) { record.playerData.setTag("MPMData", tag); } } record.dirty = true; record.resetUnload(); } }
1,490
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerRequestActions.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/actions/ServerHandlerRequestActions.java
package mchorse.blockbuster.network.server.recording.actions; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.recording.actions.PacketActionList; import mchorse.blockbuster.network.common.recording.actions.PacketRequestActions; import mchorse.blockbuster.recording.RecordUtils; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerRequestActions extends ServerMessageHandler<PacketRequestActions> { @Override public void run(EntityPlayerMP player, PacketRequestActions message) { if (!OpHelper.isPlayerOp(player)) { return; } Dispatcher.sendTo(new PacketActionList(RecordUtils.getReplays()), player); } }
820
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerActionsChange.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/actions/ServerHandlerActionsChange.java
package mchorse.blockbuster.network.server.recording.actions; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordTimeline.Selection; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.recording.actions.PacketActionsChange; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.actions.Action; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.network.ServerMessageHandler; import mchorse.mclib.utils.OpHelper; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.List; public class ServerHandlerActionsChange extends ServerMessageHandler<PacketActionsChange> { @Override public void run(EntityPlayerMP player, PacketActionsChange message) { if (!OpHelper.isPlayerOp(player)) { return; } Record record = null; try { record = CommonProxy.manager.get(message.getFilename()); } catch (Exception e) {} if (record == null) { return; } if (message.getFromTick() >= 0) { switch (message.getStatus()) { case DELETE: record.removeActionsMask(message.getFromTick(), message.getMask()); break; case ADD: if (message.getIndex() != -1) { if (message.containsOneAction()) { record.addActionCollection(message.getFromTick(), message.getIndex(), message.getActions()); } } else { record.addActionCollection(message.getFromTick(), message.getActions()); } break; case EDIT: if (message.getIndex() != -1) { if (message.containsOneAction()) { record.replaceAction(message.getFromTick(), message.getIndex(), message.getActions().get(0).get(0)); } } break; } try { RecordUtils.saveRecord(record, false, false); } catch (Exception e) { e.printStackTrace(); } } } /** * Send a deletion package to the server */ @SideOnly(Side.CLIENT) public static void deleteActions(Record record, int from, List<List<Boolean>> mask) { record.removeActionsMask(from, mask); Dispatcher.sendToServer(new PacketActionsChange(record.filename, from, mask)); } /** * Send a package to the server to add the given actions at the given tick */ @SideOnly(Side.CLIENT) public static void addActions(List<List<Action>> actions, Record record, int tick) { record.addActionCollection(tick, actions); Dispatcher.sendToServer(new PacketActionsChange(record.filename, tick, actions, PacketActionsChange.Type.ADD)); } @SideOnly(Side.CLIENT) public static void addActions(List<List<Action>> actions, Record record, int tick, int index) { if (index == -1) { addActions(actions, record, tick); } else { record.addActionCollection(tick, index, actions); Dispatcher.sendToServer(new PacketActionsChange(record.filename, tick, index, actions, PacketActionsChange.Type.ADD)); } } /** * Send a package to the server to add an action at a specific index * @param action * @param record * @param tick * @param index */ @SideOnly(Side.CLIENT) public static void addAction(Action action, Record record, int tick, int index) { record.addAction(tick, index, action); Dispatcher.sendToServer(new PacketActionsChange(record.filename, tick, index, action, PacketActionsChange.Type.ADD)); } @SideOnly(Side.CLIENT) public static void editAction(Action action, Record record, int tick, int index) { record.replaceAction(tick, index, action); Dispatcher.sendToServer(new PacketActionsChange(record.filename, tick, index, action, PacketActionsChange.Type.EDIT)); } }
4,612
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ServerHandlerRequestAction.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/network/server/recording/actions/ServerHandlerRequestAction.java
package mchorse.blockbuster.network.server.recording.actions; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.recording.actions.PacketActions; import mchorse.blockbuster.network.common.recording.actions.PacketRequestAction; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.network.ServerMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; public class ServerHandlerRequestAction extends ServerMessageHandler<PacketRequestAction> { @Override public void run(EntityPlayerMP player, PacketRequestAction message) { Record record = null; try { record = CommonProxy.manager.get(message.filename); } catch (Exception e) {} if (record != null) { Dispatcher.sendTo(new PacketActions(message.filename, record.actions, message.open), player); } } }
971
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
AudioHandler.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/audio/AudioHandler.java
package mchorse.blockbuster.audio; import io.netty.buffer.ByteBuf; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.audio.PacketAudio; import mchorse.mclib.config.values.ValueInt; import mchorse.mclib.config.values.ValueString; import mchorse.mclib.math.functions.limit.Min; import mchorse.mclib.network.IByteBufSerializable; import mchorse.mclib.network.INBTSerializable; import mchorse.mclib.utils.ForgeUtils; import mchorse.mclib.utils.ICopy; import mchorse.mclib.utils.LatencyTimer; import mchorse.mclib.utils.MathUtils; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagFloat; import net.minecraft.server.management.PlayerList; import net.minecraft.world.WorldServer; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; /** * This class is responsible for handling an audio, for example, for the scene. */ public class AudioHandler implements ICopy<AudioHandler>, INBTSerializable, IByteBufSerializable { /** * Cache of the current audio state. This does not need to be serialized */ private AudioState audioState = AudioState.STOP; private final ValueInt audioShift = new ValueInt("audio_shift"); private final ValueString audio = new ValueString("audio_name"); /** * The global tick and not the tick relative to the audio timeline. * This is used to determine when to play if there is a negative {@link #audioShift}, which signifies a delay. */ private int tick; public String getAudioName() { return this.audio.get(); } public void setAudioName(String audio) { this.audio.set((audio == null) ? "" : audio); } public int getAudioShift() { return this.audioShift.get(); } public void setAudioShift(int audioShift) { this.audioShift.set(audioShift); } public AudioState getAudioState() { return this.audioState; } public boolean hasAudio() { return this.audio.get() != null && !this.audio.get().isEmpty(); } public boolean isPlaying() { switch (this.audioState) { case REWIND: case RESUME_SET: case RESUME: case SET: return true; case PAUSE: case STOP: case PAUSE_SET: return false; } return false; } public void pauseAudio() { this.setAudioStateTick(AudioState.PAUSE, this.tick); } /** * Pause the audio at a certain tick. * @param tick The global tick and not the tick relative to the audio timeline. * This needs to be the global tick to determine whether the audio can play due to delayed audio shift. */ public void pauseAudio(int tick) { this.setAudioStateTick(AudioState.PAUSE_SET, tick); } /** * Resume playing at a certain tick. * @param tick the tick to resume playing again at. * The global tick and not the tick relative to the audio timeline. * This needs to be the global tick to determine whether the audio can play due to delayed audio shift. */ public void resume(int tick) { this.setAudioStateTick(AudioState.RESUME_SET, tick); } /** * Stops the audio. */ public void stopAudio() { this.audioState = AudioState.STOP; this.sendAudioState(AudioState.STOP, Blockbuster.audioSync.get()); } /** * Go to a tick. This can happen while in paused/stopped state or in playing state. * @param tick the global tick and not the tick relative to the audio timeline. * This needs to be the global tick to determine whether the audio can play due to delayed audio shift. */ public void goTo(int tick) { /* * It is important that the audio state SET is only used when setting the audio while it is playing. * AudioState.SET <=> playing */ this.setAudioStateTick(this.isPlaying() ? AudioState.SET : AudioState.PAUSE_SET, tick); } /** * * @param tick the global tick and not the tick relative to the audio timeline. * This needs to be the global tick to determine whether the audio can play due to delayed audio shift. */ public void startAudio(int tick) { this.setAudioStateTick(AudioState.REWIND, tick); } /** * Sets the tick, audiostate and sends them to the players with {@link #sendAudioState(AudioState, boolean)}. * If the tick is smaller than the delay, when {@link #audioShift} is negative, it stops the audio. * If the tick is greater than the delay it will allow the state to be synchronised. * @param state * @param tick The global tick and not the tick relative to the audio timeline. * This needs to be the global tick to determine whether the audio can play due to delayed audio shift. */ private void setAudioStateTick(AudioState state, int tick) { this.tick = tick; if (this.audioShift.get() < 0 && tick < -this.audioShift.get()) { this.stopAudio(); return; } this.audioState = state; this.sendAudioState(state, Blockbuster.audioSync.get()); } /** * This method must be called, preferably on the logical server side! * This updates the tick and starts the audio if there was a negative {@link #audioShift}. * A negative {@link #audioShift} signifies a delay. If the tick is greater than the delay the audio will be started. */ public void update() { if (this.audioShift.get() < 0 && this.tick >= -this.audioShift.get() && !this.isPlaying()) { this.startAudio(this.tick); } this.tick++; } /** * Sends the audio, if present, to all players on the server * and set {@link #audioState} to the provided state. * @param state * @param sync whether to try and sync the audio with server and client. */ private void sendAudioState(AudioState state, boolean sync) { if (!this.hasAudio()) { return; } for (EntityPlayerMP player : ForgeUtils.getServerPlayers()) { this.sendAudioStateToPlayer(state, (sync) ? new LatencyTimer() : null, player); } } /** * Send the current audio state to the player. This is useful when a player joins a server with audio already playing. * @param player */ public void syncPlayer(EntityPlayerMP player) { AudioState state = this.audioState; /* * convert to SET equivalent states so a player who joins the server * gets the audio state and the correct tick set */ switch (this.audioState) { case PAUSE: state = AudioState.PAUSE_SET; break; case RESUME: state = AudioState.RESUME_SET; break; } this.sendAudioStateToPlayer(state, (Blockbuster.audioSync.get()) ? new LatencyTimer() : null, player); } /** * Send the audio to the provided player * @param state * @param latencyTimer a timer to measure (approximately) the delay to sync the audio properly * @param player the entity player the audio should be sent to */ private void sendAudioStateToPlayer(AudioState state, @Nullable LatencyTimer latencyTimer, EntityPlayerMP player) { if (!this.hasAudio()) { return; } /** * Important: this expects that the calling methods already checked the tick and state * so that, for example, an audio with delay of 10 will not try to send a state * that will play the audio before tick 10 is reached. If this is violated, * the shift passed to {@link AudioLibrary} might become negative. */ int shift = 0; switch (state) { case REWIND: case RESUME_SET: case PAUSE_SET: case SET: shift = this.tick; break; case PAUSE: case STOP: shift = -this.audioShift.get(); break; } PacketAudio packet = new PacketAudio(this.audio.get(), state, shift + this.audioShift.get(), latencyTimer); if (player != null) { Dispatcher.sendTo(packet, player); } } @Override public AudioHandler copy() { AudioHandler clone = new AudioHandler(); clone.copy(this); return clone; } @Override public void copy(AudioHandler origin) { this.audio.copy(origin.audio); this.audioState = origin.audioState; this.audioShift.copy(origin.audioShift); this.tick = origin.tick; } @Override public void fromNBT(NBTTagCompound compound) { this.audio.set(compound.hasKey("Audio") ? compound.getString("Audio") : ""); if (compound.hasKey("AudioShift")) { if (compound.getTag("AudioShift") instanceof NBTTagFloat) { this.audioShift.set((int) (compound.getFloat("AudioShift") * 20)); } else { this.audioShift.set(compound.getInteger("AudioShift")); } } } @Override public NBTTagCompound toNBT(NBTTagCompound compound) { if (this.audio.hasChanged()) { compound.setTag("Audio", this.audio.valueToNBT()); } if (this.audioShift.hasChanged()) { compound.setTag("AudioShift", this.audioShift.valueToNBT()); } return compound; } @Override public void fromBytes(ByteBuf byteBuf) { this.audio.fromBytes(byteBuf); this.audioShift.fromBytes(byteBuf); } @Override public void toBytes(ByteBuf byteBuf) { this.audio.toBytes(byteBuf); this.audioShift.toBytes(byteBuf); } }
10,443
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
AudioState.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/audio/AudioState.java
package mchorse.blockbuster.audio; public enum AudioState { REWIND, PAUSE, PAUSE_SET, RESUME, RESUME_SET, SET, STOP }
122
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
AudioRenderer.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/audio/AudioRenderer.java
package mchorse.blockbuster.audio; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.ClientProxy; import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw; import mchorse.mclib.utils.ColorUtils; import mchorse.mclib.utils.wav.Waveform; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.StringUtils; @SideOnly(Side.CLIENT) public class AudioRenderer { public static void renderAll(int x, int y, int w, int h, int sw, int sh) { if (!Blockbuster.audioWaveformVisible.get()) { return; } /* Make the anchor at the bottom */ y -= h; for (AudioFile file : ClientProxy.audio.files.values()) { if (!file.isEmpty() && !file.player.isStopped()) { AudioRenderer.renderWaveform(file, x, y, w, h, sw, sh); y -= h + 5; } } } public static void renderWaveform(AudioFile file, int x, int y, int w, int h, int sw, int sh) { if (file == null || file.isEmpty()) { return; } final float brightness = 0.45F; int half = w / 2; /* Draw background */ GuiDraw.drawVerticalGradientRect(x + 2, y + 2, x + w - 2, y + h, 0, ColorUtils.HALF_BLACK); Gui.drawRect(x + 1, y, x + 2, y + h, 0xaaffffff); Gui.drawRect(x + w - 2, y, x + w - 1, y + h, 0xaaffffff); Gui.drawRect(x, y + h - 1, x + w, y + h, 0xffffffff); GuiDraw.scissor(x + 2, y + 2, w - 4, h - 4, sw, sh); Waveform wave = file.waveform; if (!wave.isCreated()) { wave.render(); } float playback = file.player.getPlaybackPosition(); int offset = (int) (playback * wave.getPixelsPerSecond()); int waveW = file.waveform.getWidth(); GlStateManager.color(1, 1, 1, 1); GlStateManager.enableTexture2D(); GlStateManager.enableAlpha(); GlStateManager.enableBlend(); /* Draw the waveform */ int runningOffset = waveW - offset; if (runningOffset > 0) { file.waveform.draw(x + half, y, offset, 0, Math.min(runningOffset, half), h, h); } /* Draw the passed waveform */ if (offset > 0) { int xx = offset > half ? x : x + half - offset; int oo = offset > half ? offset - half : 0; int ww = offset > half ? half : offset; GlStateManager.color(brightness, brightness, brightness); file.waveform.draw(xx, y, oo, 0, ww, h, h); GlStateManager.color(1, 1, 1); } GuiDraw.unscissor(sw, sh); Gui.drawRect(x + half, y + 1, x + half + 1, y + h - 1, 0xff57f52a); FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; if (Blockbuster.audioWaveformFilename.get()) { GuiDraw.drawTextBackground(fontRenderer, file.name, x + 8, y + h / 2 - 4, 0xffffff, 0x99000000); } if (Blockbuster.audioWaveformTime.get()) { int tick = (int) Math.floor(playback * 20); int seconds = tick / 20; int milliseconds = (int) (tick % 20 == 0 ? 0 : tick % 20 * 5D); String tickLabel = tick + "t (" + seconds + "." + StringUtils.leftPad(String.valueOf(milliseconds), 2, "0") + "s)"; GuiDraw.drawTextBackground(fontRenderer, tickLabel, x + w - 8 - fontRenderer.getStringWidth(tickLabel), y + h / 2 - 4, 0xffffff, 0x99000000); } } }
3,786
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
AudioFile.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/audio/AudioFile.java
package mchorse.blockbuster.audio; import mchorse.mclib.utils.wav.WavePlayer; import mchorse.mclib.utils.wav.Waveform; import org.lwjgl.openal.AL10; import java.io.File; public class AudioFile { public String name; public File file; public WavePlayer player; public Waveform waveform; public long update; private boolean wasPaused; public AudioFile(String name, File file, WavePlayer player, Waveform waveform, long update) { this.name = name; this.file = file; this.player = player; this.waveform = waveform; this.update = update; } public boolean canBeUpdated() { return this.update < this.file.lastModified(); } public boolean isEmpty() { return this.player == null || this.waveform == null; } public void delete() { if (this.player != null) { this.player.delete(); this.player = null; } if (this.waveform != null) { this.waveform.delete(); this.waveform = null; } } public void pause(boolean pause) { if (this.player == null) return; int state = this.player.getSourceState(); if (!pause && this.wasPaused) { this.wasPaused = false; return; } this.wasPaused = pause && state == AL10.AL_PAUSED; if (pause && state == AL10.AL_PLAYING) { this.player.pause(); } else if (!pause && state == AL10.AL_PAUSED) { this.player.play(); } } }
1,627
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
AudioLibrary.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/audio/AudioLibrary.java
package mchorse.blockbuster.audio; import mchorse.blockbuster.Blockbuster; import mchorse.mclib.utils.LatencyTimer; import mchorse.mclib.utils.wav.Wave; import mchorse.mclib.utils.wav.WavePlayer; import mchorse.mclib.utils.wav.WaveReader; import mchorse.mclib.utils.wav.Waveform; import javax.annotation.Nullable; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class AudioLibrary { public File folder; public Map<String, AudioFile> files = new HashMap<String, AudioFile>(); public AudioLibrary(File folder) { this.folder = folder; this.folder.mkdirs(); } public List<File> getFiles() { File[] files = this.folder.listFiles(); if (files == null) { return Collections.emptyList(); } List<File> list = new ArrayList<File>(); for (File file : files) { if (!file.getName().endsWith(".wav")) { continue; } list.add(file); } return list; } public List<String> getFileNames() { List<String> list = new ArrayList<String>(); for (File file : this.getFiles()) { String name = file.getName(); list.add(name.substring(0, name.length() - 4)); } return list; } private AudioFile load(String name, File file) { if (!file.isFile()) { return null; } AudioFile audio; try { Wave wave = new WaveReader().read(new FileInputStream(file)); if (wave.getBytesPerSample() > 2) { wave = wave.convertTo16(); } WavePlayer player = new WavePlayer().initialize(wave); Waveform waveform = new Waveform(); waveform.populate(wave, Blockbuster.audioWaveformDensity.get(), 40); audio = new AudioFile(name + ".wav", file, player, waveform, file.lastModified()); } catch (Exception e) { e.printStackTrace(); /* Empty */ audio = new AudioFile(name + ".wav", file, null, null, file.lastModified()); } this.files.put(name, audio); return audio; } /** * * @param audio name of the file (without .wav file ending) * @param state play, pause, resume etc. the audio * @param shift in ticks * @param delay for syncing purposes, if not used, pass null as value * @return false if the file is null or empty */ public boolean handleAudio(String audio, AudioState state, int shift, @Nullable LatencyTimer delay) { AudioFile file = this.files.get(audio); if (file == null || file.canBeUpdated()) { file = this.load(audio, new File(this.folder, audio + ".wav")); } if (file == null || file.isEmpty()) { return false; } WavePlayer player = file.player; float seconds = shift / 20F; float elapsedDelay = (delay != null) ? delay.getElapsedTime() / 1000F : 0F; System.out.println("Received audio latency of: " + elapsedDelay + " seconds"); this.handleAudioState(state, player, seconds, elapsedDelay); return true; } private void handleAudioState(AudioState state, WavePlayer player, float seconds, float elapsedDelay) { switch (state) { case REWIND: player.stop(); player.play(); player.setPlaybackPosition(seconds + elapsedDelay); break; case PAUSE: elapsedDelay = (player.isPlaying()) ? elapsedDelay : 0; player.pause(); player.setPlaybackPosition(((seconds == 0) ? player.getPlaybackPosition() : seconds) - elapsedDelay); break; case PAUSE_SET: if (player.isStopped()) { player.play(); } player.pause(); player.setPlaybackPosition(seconds); break; case RESUME: player.play(); player.setPlaybackPosition(player.getPlaybackPosition() + elapsedDelay); break; case RESUME_SET: player.play(); player.setPlaybackPosition(seconds + elapsedDelay); break; case SET: elapsedDelay = (player.isPlaying()) ? elapsedDelay : 0; player.setPlaybackPosition(seconds + elapsedDelay); break; case STOP: player.stop(); break; } } public void reset() { for (AudioFile file : this.files.values()) { file.delete(); } this.files.clear(); } public void pause(boolean pause) { for (AudioFile file : this.files.values()) { file.pause(pause); } } }
5,217
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
CapabilityHandler.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/capabilities/CapabilityHandler.java
package mchorse.blockbuster.capabilities; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.capabilities.recording.IRecording; import mchorse.blockbuster.capabilities.recording.Recording; import mchorse.blockbuster.capabilities.recording.RecordingProvider; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.scene.PacketSceneCast; import mchorse.blockbuster.network.common.structure.PacketStructureList; import mchorse.blockbuster.network.server.ServerHandlerStructureRequest; import mchorse.blockbuster.recording.RecordPlayer; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.scene.Scene; import mchorse.blockbuster.recording.scene.SceneLocation; import mchorse.blockbuster.utils.EntityUtils; import mchorse.mclib.utils.LatencyTimer; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.player.PlayerEvent.StartTracking; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import java.util.Map; /** * Capability handler class * * This class is responsible for managing capabilities, i.e. attaching * capabilities and syncing values on the client. */ public class CapabilityHandler { public static final ResourceLocation RECORDING_CAP = new ResourceLocation(Blockbuster.MOD_ID, "recording_capability"); /** * Attach capabilities (well, only one, right now) */ @SubscribeEvent @SuppressWarnings("deprecation") public void attachPlayerCapability(AttachCapabilitiesEvent<Entity> event) { if (!(event.getObject() instanceof EntityPlayer)) { return; } event.addCapability(RECORDING_CAP, new RecordingProvider()); } /** * When player logs in, sent him his server counter partner's values. */ @SubscribeEvent public void playerLogsIn(PlayerLoggedInEvent event) { EntityPlayerMP player = (EntityPlayerMP) event.player; IRecording recording = Recording.get(player); Dispatcher.sendTo(new PacketStructureList(ServerHandlerStructureRequest.getAllStructures()), player); if (recording.getLastScene() != null) { Scene scene = CommonProxy.scenes.get(recording.getLastScene(), player.world); if (scene != null) { Dispatcher.sendTo(new PacketSceneCast(new SceneLocation(scene)).open(false), player); } } /* send playing audio to client */ for(Map.Entry<String, Scene> entry : CommonProxy.scenes.getScenes().entrySet()) { entry.getValue().syncAudio(player); } } /** * When player starts tracking an actor, server has to send actor's record * frames to the player */ @SubscribeEvent public void playerStartsTracking(StartTracking event) { Entity target = event.getTarget(); EntityPlayerMP player = (EntityPlayerMP) event.getEntityPlayer(); if (target instanceof EntityLivingBase) { RecordPlayer playback = EntityUtils.getRecordPlayer((EntityLivingBase) target); if (playback != null) { RecordUtils.sendRequestedRecord(target.getEntityId(), playback.record.filename, player); } } } }
3,685
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Recording.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/capabilities/recording/Recording.java
package mchorse.blockbuster.capabilities.recording; import java.util.HashMap; import java.util.Map; import mchorse.blockbuster.recording.RecordPlayer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; /** * Default implementation of {@link IRecording} */ public class Recording implements IRecording { public String lastScene = ""; public Map<String, ItemInfo> recordings = new HashMap<String, ItemInfo>(); public BlockPos teleportPos; public RecordPlayer player; public boolean fakePlayer; public static IRecording get(EntityPlayer player) { return player.getCapability(RecordingProvider.RECORDING, null); } @Override public String getLastScene() { return this.lastScene; } @Override public void setLastScene(String scene) { if (scene == null) { return; } this.lastScene = scene; } @Override public boolean hasRecording(String filename) { return this.recordings.containsKey(filename); } @Override public long recordingTimestamp(String filename) { return this.recordings.get(filename).timestamp; } @Override public void addRecording(String filename, long timestamp) { if (this.hasRecording(filename)) { this.updateRecordingTimestamp(filename, timestamp); } else { this.recordings.put(filename, new ItemInfo(filename, timestamp)); } } @Override public void removeRecording(String filename) { this.recordings.remove(filename); } @Override public void removeRecordings() { this.recordings.clear(); } @Override public void updateRecordingTimestamp(String filename, long timestamp) { if (this.hasRecording(filename)) { this.recordings.get(filename).timestamp = timestamp; } } @Override public void setLastTeleportedBlockPos(BlockPos pos) { this.teleportPos = pos; } @Override public BlockPos getLastTeleportedBlockPos() { return this.teleportPos; } @Override public void setRecordPlayer(RecordPlayer player) { this.player = player; } @Override public RecordPlayer getRecordPlayer() { return this.player; } @Override public boolean isFakePlayer() { return this.fakePlayer; } @Override public void setFakePlayer(boolean fakePlayer) { this.fakePlayer = fakePlayer; } /** * Item information class * * Instance of this class is responsible for storing information about a * file item like camera profile or recording with timestamp of when * it was changed. */ public static class ItemInfo { public String filename; public long timestamp; public ItemInfo() { this("", -1); } public ItemInfo(String filename, long timestamp) { this.filename = filename; this.timestamp = timestamp; } } }
3,189
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
IRecording.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/capabilities/recording/IRecording.java
package mchorse.blockbuster.capabilities.recording; import mchorse.blockbuster.recording.RecordPlayer; import net.minecraft.util.math.BlockPos; /** * Recording capability * * This capability is responsible for tracking client player's resources such * as loaded records and camera profile (and also some data related to tracking * the changes of these resources). * * I think it will be server-side only capability (no need to sync with client). */ public interface IRecording { /** * Get last edited scene */ public String getLastScene(); /** * Set last edited scene */ public void setLastScene(String scene); /** * Does player has loaded recording? */ public boolean hasRecording(String filename); /** * What is the last time given recording was updated? */ public long recordingTimestamp(String filename); /** * Add a recording */ public void addRecording(String filename, long timestamp); /** * Remove a recording */ public void removeRecording(String filename); /** * Remove all recordings */ public void removeRecordings(); /** * Update given recording's timestamp */ public void updateRecordingTimestamp(String filename, long timestamp); /** * Set last teleported block position */ public void setLastTeleportedBlockPos(BlockPos pos); /** * Get last teleported block position */ public BlockPos getLastTeleportedBlockPos(); /** * Set record player which will animate this player */ public void setRecordPlayer(RecordPlayer player); /** * Get the record player which animates this player */ public RecordPlayer getRecordPlayer(); /** * Whether this player is fake */ public boolean isFakePlayer(); /** * Set fake player */ public void setFakePlayer(boolean fakePlayer); }
1,957
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
RecordingProvider.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/capabilities/recording/RecordingProvider.java
package mchorse.blockbuster.capabilities.recording; import mchorse.metamorph.capabilities.morphing.MorphingProvider; import net.minecraft.nbt.NBTBase; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.fml.relauncher.SideOnly; /** * Recording provider * * Basic version of a capability provider. Most of the code is taken from * {@link MorphingProvider}. */ public class RecordingProvider implements ICapabilitySerializable<NBTBase> { @CapabilityInject(IRecording.class) public static final Capability<IRecording> RECORDING = null; private IRecording instance = RECORDING.getDefaultInstance(); @Override public boolean hasCapability(Capability<?> capability, EnumFacing facing) { return capability == RECORDING; } @Override public <T> T getCapability(Capability<T> capability, EnumFacing facing) { return capability == RECORDING ? RECORDING.<T>cast(this.instance) : null; } @Override public NBTBase serializeNBT() { return RECORDING.getStorage().writeNBT(RECORDING, this.instance, null); } @Override public void deserializeNBT(NBTBase nbt) { RECORDING.getStorage().readNBT(RECORDING, this.instance, null, nbt); } }
1,507
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
RecordingStorage.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/capabilities/recording/RecordingStorage.java
package mchorse.blockbuster.capabilities.recording; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability.IStorage; import net.minecraftforge.common.util.Constants; /** * Recording capability storage * * This storage saves only current camera profile's name, because the other * fields like the timestamp of camera profile or recording information does * needed only during runtime. * * Basically, when client joins, he doesn't have any of that information except * latest camera profile he had in previous session, so we just don't store it. */ public class RecordingStorage implements IStorage<IRecording> { @Override public NBTBase writeNBT(Capability<IRecording> capability, IRecording instance, EnumFacing side) { NBTTagCompound tag = new NBTTagCompound(); tag.setString("Scene", instance.getLastScene()); return tag; } @Override public void readNBT(Capability<IRecording> capability, IRecording instance, EnumFacing side, NBTBase nbt) { if (nbt instanceof NBTTagCompound) { NBTTagCompound tag = (NBTTagCompound) nbt; if (tag.hasKey("Scene", Constants.NBT.TAG_STRING)) { instance.setLastScene(tag.getString("Scene")); } } } }
1,463
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Model.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/Model.java
package mchorse.blockbuster.api; import com.google.common.base.MoreObjects; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import mchorse.blockbuster.api.formats.obj.OBJMaterial; import mchorse.blockbuster.api.json.ModelAdapter; import mchorse.blockbuster.api.json.ModelLimbAdapter; import mchorse.mclib.utils.resources.RLUtils; import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * Model class * * This class is a domain object that holds all information about the model like * its name, texture size, limbs, poses, interests and stuff. */ public class Model { /** * Poses that are required by custom models */ public static final List<String> REQUIRED_POSES = Arrays.asList("standing"); /** * Scheme version. Would be used in future versions for extracting and * exporting purposes. */ @Expose public String scheme = "1.3"; /** * Not really sure what to do with this one. */ @Expose public String name = ""; /** * Default texture for this model */ @Expose public ResourceLocation defaultTexture; /** * Texture size. First element is width, second is height. */ @Expose public int[] texture = new int[] {64, 32}; /** * Extrude max factor (allows to limit how many extruded sub levels you can have) */ @Expose public int extrudeMaxFactor = 1; /** * Extrude inwards factor (allows to extrude inwards more bits) */ @Expose public int extrudeInwards = 1; /** * Scale of the model */ @Expose public float[] scale = new float[] {1, 1, 1}; /** * Scale to be displayed in GUI */ @Expose public float scaleGui = 1; /** * Class for the custom model */ @Expose public String model = ""; /** * Does this model provides OBJ model */ @Expose public boolean providesObj = false; /** * Does this model provides MTL file */ @Expose public boolean providesMtl = false; @Expose public boolean legacyObj = true; /** * Skins folder */ @Expose public String skins = ""; @Expose public Map<String, ModelLimb> limbs = new HashMap<String, ModelLimb>(); @Expose public Map<String, ModelPose> poses = new HashMap<String, ModelPose>(); @Expose public Map<String, String> presets = new HashMap<String, String>(); public Map<String, OBJMaterial> materials = new HashMap<String, OBJMaterial>(); public List<String> shapes = new ArrayList<String>(); /** * Parse model from input stream */ public static Model parse(InputStream stream) throws Exception { Scanner scanner = new Scanner(stream, "UTF-8"); Model model = parse(scanner.useDelimiter("\\A").next()); scanner.close(); return model; } /** * This method parses an instance of Model class from provided JSON string. * This method also checks if model has all required poses for playing. */ public static Model parse(String json) throws Exception { Gson gson = new GsonBuilder().registerTypeAdapter(Model.class, new ModelAdapter()).registerTypeAdapter(ModelLimb.class, new ModelLimbAdapter()).excludeFieldsWithoutExposeAnnotation().create(); Model data = gson.fromJson(json, Model.class); for (String key : REQUIRED_POSES) { if (!data.poses.containsKey(key)) { throw new Exception(I18n.format("blockbuster.parsing.lacks_pose", data.name, key)); } } if (data.limbs.isEmpty()) { throw new Exception(I18n.format("blockbuster.parsing.lacks_limbs", data.name)); } data.fillInMissing(); return data; } /** * Checks whether this model has textured materials */ public boolean hasTexturedMaterials() { if (this.materials.isEmpty()) { return false; } for (OBJMaterial material : this.materials.values()) { if (material.useTexture) return true; } return false; } /** * Add a limb into a model */ public ModelLimb addLimb(String name) { return this.addLimb(new ModelLimb(name)); } /** * Add a limb into a model */ public ModelLimb addLimb(ModelLimb limb) { this.limbs.put(limb.name, limb); for (ModelPose pose : this.poses.values()) { pose.limbs.put(limb.name, new ModelTransform()); } return limb; } /** * Remove limb from a model * * If given any limb in the model is child of this limb, then they're * also getting removed. */ public void removeLimb(ModelLimb limb) { this.limbs.remove(limb.name); List<ModelLimb> limbsToRemove = new ArrayList<ModelLimb>(); for (ModelLimb child : this.limbs.values()) { if (child.parent.equals(limb.name)) { limbsToRemove.add(child); } } for (ModelPose pose : this.poses.values()) { pose.limbs.remove(limb.name); } for (ModelLimb limbToRemove : limbsToRemove) { this.removeLimb(limbToRemove); } } /** * Rename given limb (this limb should already exist in this model) * @return */ public boolean renameLimb(ModelLimb limb, String newName) { if (this.limbs.containsKey(newName) || !this.limbs.containsValue(limb)) { return false; } /* Rename limb name in poses */ for (ModelPose pose : this.poses.values()) { ModelTransform transform = pose.limbs.remove(limb.name); pose.limbs.put(newName, transform); } /* Rename all children limbs */ for (ModelLimb child : this.limbs.values()) { if (child.parent.equals(limb.name)) { child.parent = newName; } } /* And finally remap the limb name to the new name */ this.limbs.remove(limb.name); this.limbs.put(newName, limb); limb.name = newName; return true; } /** * Returns amount of limbs given limb hosts */ public int getLimbCount(ModelLimb parent) { int count = 1; for (ModelLimb child : this.limbs.values()) { if (child.parent.equals(parent.name)) { count += this.getLimbCount(child); } } return count; } /** * Fill in missing transforms and assign name to every limb */ public void fillInMissing() { for (Map.Entry<String, ModelLimb> entry : this.limbs.entrySet()) { String key = entry.getKey(); for (ModelPose pose : this.poses.values()) { if (!pose.limbs.containsKey(key)) { pose.limbs.put(key, new ModelTransform()); } } entry.getValue().name = key; } } /** * Get pose, or return default pose (which is the "standing" pose) */ public ModelPose getPose(String key) { ModelPose pose = this.poses.get(key); return pose == null ? this.poses.get("standing") : pose; } /** * Clone a model */ public Model copy() { Model b = new Model(); b.texture = new int[] {this.texture[0], this.texture[1]}; b.scale = new float[] {this.scale[0], this.scale[1], this.scale[2]}; b.scaleGui = this.scaleGui; b.name = this.name; b.scheme = this.scheme; b.model = this.model; b.defaultTexture = this.defaultTexture == null ? null : RLUtils.clone(this.defaultTexture); b.providesObj = this.providesObj; b.providesMtl = this.providesMtl; b.legacyObj = this.legacyObj; b.skins = this.skins; for (Map.Entry<String, ModelLimb> entry : this.limbs.entrySet()) { b.limbs.put(entry.getKey(), entry.getValue().clone()); } for (Map.Entry<String, ModelPose> entry : this.poses.entrySet()) { b.poses.put(entry.getKey(), entry.getValue().copy()); } b.presets.putAll(this.presets); b.shapes.addAll(this.shapes); return b; } public List<String> getChildren(String limb) { Map<String, List<String>> tree = new HashMap<String, List<String>>(); for (Map.Entry<String, ModelLimb> entry : this.limbs.entrySet()) { String parent = entry.getValue().parent; if (tree.get(parent) == null) { tree.put(parent, new ArrayList<String>()); } tree.get(parent).add(entry.getKey()); } List<String> children = new ArrayList<String>(); this.getChildren(tree, limb, children); return children; } private void getChildren(Map<String, List<String>> tree, String limb, List<String> out) { List<String> children = tree.get(limb); if (children != null) { out.addAll(children); for (String child : children) { getChildren(tree, child, out); } } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("scheme", this.scheme).add("name", this.name).add("texture", Arrays.toString(this.texture)).add("limbs", this.limbs).add("poses", this.poses).toString(); } }
10,108
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelHandler.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelHandler.java
package mchorse.blockbuster.api; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.HashMap; import java.util.Map; /** * This class responsible for storing domain custom models and sending models to * players who are logged in. */ public class ModelHandler { public static long lastUpdate; /** * Cached models, they're loaded from stuffs */ public Map<String, Model> models = new HashMap<String, Model>(); /** * Actors pack from which ModelHandler loads its models */ public ModelPack pack; /** * Load user and default provided models into model map */ public void loadModels(ModelPack pack, boolean force) { pack.reload(); /* Load user provided models */ for (Map.Entry<String, IModelLazyLoader> entry : (force ? pack.models : pack.changed).entrySet()) { IModelLazyLoader loader = entry.getValue(); try { if (force) { this.removeModel(entry.getKey()); } this.addModel(entry.getKey(), loader); } catch (Exception e) { e.printStackTrace(); System.out.println("Error happened with " + entry.getKey()); } } /* Remove unloaded models */ for (String key : pack.removed) { this.removeModel(key); } lastUpdate = System.currentTimeMillis(); } /** * Add model to the model handler */ public void addModel(String key, IModelLazyLoader loader) throws Exception { Model model = loader.loadModel(key); this.models.put(key, model); this.addMorph(key, model); } protected void addMorph(String key, Model model) { Blockbuster.proxy.factory.section.add(key, model, false); } /** * Remove model from model handler */ public void removeModel(String key) { Model model = this.models.remove(key); if (model != null) { Blockbuster.proxy.factory.section.remove(key); } } /** * Loads local models when connecting to the server */ @SubscribeEvent @SideOnly(Side.CLIENT) public void onClientConnect(ClientConnectedToServerEvent event) { Blockbuster.proxy.loadModels(false); Blockbuster.proxy.particles.reload(); } }
2,782
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelUserItem.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelUserItem.java
package mchorse.blockbuster.api; import java.util.List; public class ModelUserItem { public String obj; public String mtl; public String vox; public List<String> shapes; }
189
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelPose.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelPose.java
package mchorse.blockbuster.api; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.base.MoreObjects; import mchorse.blockbuster.api.formats.obj.ShapeKey; import mchorse.mclib.utils.NBTUtils; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants; /** * Pose class * * This class is responsible for holding transformation about every limb * available in the main model. Model parser should put default transforms * for limbs that don't have transformations. */ public class ModelPose { public float[] size = new float[] {1, 1, 1}; public Map<String, ModelTransform> limbs = new HashMap<String, ModelTransform>(); /** * Shapes configurations */ public final List<ShapeKey> shapes = new ArrayList<ShapeKey>(); public void copy(ModelPose pose) { for (int i = 0, c = Math.min(pose.size.length, this.size.length); i < c; i++) { this.size[i] = pose.size[i]; } for (Map.Entry<String, ModelTransform> entry : this.limbs.entrySet()) { ModelTransform otherTransform = pose.limbs.get(entry.getKey()); if (otherTransform != null) { entry.getValue().copy(otherTransform); } } } /** * Fill in missing transforms */ public void fillInMissing(ModelPose pose) { for (Map.Entry<String, ModelTransform> entry : pose.limbs.entrySet()) { String key = entry.getKey(); if (!this.limbs.containsKey(key)) { this.limbs.put(key, entry.getValue().clone()); } } } @Override public boolean equals(Object obj) { if (obj instanceof ModelPose) { ModelPose pose = (ModelPose) obj; return ModelTransform.equalFloatArray(this.size, pose.size) && this.limbs.equals(pose.limbs) && this.shapes.equals(pose.shapes); } return super.equals(obj); } /** * Clone a model pose */ public ModelPose copy() { ModelPose b = new ModelPose(); b.size = new float[] {this.size[0], this.size[1], this.size[2]}; for (Map.Entry<String, ModelTransform> entry : this.limbs.entrySet()) { b.limbs.put(entry.getKey(), entry.getValue().clone()); } for (ShapeKey key : this.shapes) { b.shapes.add(key.copy()); } return b; } public void fromNBT(NBTTagCompound tag) { if (tag.hasKey("Size", Constants.NBT.TAG_LIST)) { NBTTagList list = tag.getTagList("Size", 5); if (list.tagCount() >= 3) { NBTUtils.readFloatList(list, this.size); } } if (tag.hasKey("Poses", Constants.NBT.TAG_COMPOUND)) { this.limbs.clear(); NBTTagCompound poses = tag.getCompoundTag("Poses"); for (String key : poses.getKeySet()) { ModelTransform trans = new ModelTransform(); trans.fromNBT(poses.getCompoundTag(key)); this.limbs.put(key, trans); } } if (tag.hasKey("Shapes")) { NBTTagList shapes = tag.getTagList("Shapes", Constants.NBT.TAG_COMPOUND); this.shapes.clear(); for (int i = 0; i < shapes.tagCount(); i++) { NBTTagCompound key = shapes.getCompoundTagAt(i); if (key.hasKey("Name") && key.hasKey("Value")) { ShapeKey shapeKey = new ShapeKey(); shapeKey.fromNBT(key); this.shapes.add(shapeKey); } } } } public NBTTagCompound toNBT(NBTTagCompound tag) { NBTTagCompound poses = new NBTTagCompound(); tag.setTag("Size", NBTUtils.writeFloatList(new NBTTagList(), this.size)); tag.setTag("Poses", poses); for (Map.Entry<String, ModelTransform> entry : this.limbs.entrySet()) { poses.setTag(entry.getKey(), entry.getValue().toNBT()); } if (!this.shapes.isEmpty()) { NBTTagList shapes = new NBTTagList(); for (ShapeKey shape : this.shapes) { if (shape.value != 0) { shapes.appendTag(shape.toNBT()); } } tag.setTag("Shapes", shapes); } return tag; } @Override public String toString() { return MoreObjects.toStringHelper(this).add("size", this.size).add("limbs", this.limbs).toString(); } public void setSize(float w, float h, float d) { this.size[0] = w; this.size[1] = h; this.size[2] = d; } }
4,991
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelTransform.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelTransform.java
package mchorse.blockbuster.api; import mchorse.mclib.client.gui.framework.elements.input.GuiTransformations; import mchorse.mclib.utils.ITransformationObject; import mchorse.mclib.utils.MatrixUtils; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL11; import com.google.common.base.MoreObjects; import mchorse.mclib.utils.Interpolation; import mchorse.mclib.utils.NBTUtils; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; /** * Transform class * * This class simply holds basic transformation data for every limb. */ public class ModelTransform implements ITransformationObject { /** * Default model transform. Please don't modify its values. */ public static final ModelTransform DEFAULT = new ModelTransform(); public float[] translate = new float[] {0, 0, 0}; public float[] scale = new float[] {1, 1, 1}; public float[] rotate = new float[] {0, 0, 0}; @Override public void addTranslation(double x, double y, double z, GuiTransformations.TransformOrientation orientation) { Vector4f trans = new Vector4f((float) x,(float) y,(float) z, 1); if (orientation == GuiTransformations.TransformOrientation.LOCAL) { float rotX = (float) Math.toRadians(this.rotate[0]); float rotY = (float) Math.toRadians(this.rotate[1]); float rotZ = (float) Math.toRadians(this.rotate[2]); MatrixUtils.getRotationMatrix(rotX, rotY, rotZ, MatrixUtils.RotationOrder.XYZ).transform(trans); } this.translate[0] += trans.x; this.translate[1] += trans.y; this.translate[2] += trans.z; } public static boolean equalFloatArray(float[] a, float[] b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (Math.abs(a[i] - b[i]) > 0.0001F) { return false; } } return true; } public boolean isDefault() { return this.equals(DEFAULT); } public void copy(ModelTransform transform) { for (int i = 0; i < 3; i++) this.translate[i] = transform.translate[i]; for (int i = 0; i < 3; i++) this.scale[i] = transform.scale[i]; for (int i = 0; i < 3; i++) this.rotate[i] = transform.rotate[i]; } @Override public boolean equals(Object obj) { if (obj instanceof ModelTransform) { ModelTransform transform = (ModelTransform) obj; return equalFloatArray(this.translate, transform.translate) && equalFloatArray(this.rotate, transform.rotate) && equalFloatArray(this.scale, transform.scale); } return super.equals(obj); } /** * Clone a model transform */ @Override public ModelTransform clone() { ModelTransform b = new ModelTransform(); b.translate = new float[] {this.translate[0], this.translate[1], this.translate[2]}; b.rotate = new float[] {this.rotate[0], this.rotate[1], this.rotate[2]}; b.scale = new float[] {this.scale[0], this.scale[1], this.scale[2]}; return b; } public void fromNBT(NBTTagCompound tag) { if (tag.hasKey("P", NBT.TAG_LIST)) NBTUtils.readFloatList(tag.getTagList("P", 5), this.translate); if (tag.hasKey("S", NBT.TAG_LIST)) NBTUtils.readFloatList(tag.getTagList("S", 5), this.scale); if (tag.hasKey("R", NBT.TAG_LIST)) NBTUtils.readFloatList(tag.getTagList("R", 5), this.rotate); } public NBTTagCompound toNBT() { NBTTagCompound tag = new NBTTagCompound(); if (!this.isDefault()) { if (!equalFloatArray(DEFAULT.translate, this.translate)) tag.setTag("P", NBTUtils.writeFloatList(new NBTTagList(), this.translate)); if (!equalFloatArray(DEFAULT.scale, this.scale)) tag.setTag("S", NBTUtils.writeFloatList(new NBTTagList(), this.scale)); if (!equalFloatArray(DEFAULT.rotate, this.rotate)) tag.setTag("R", NBTUtils.writeFloatList(new NBTTagList(), this.rotate)); } return tag; } @SideOnly(Side.CLIENT) public void transform() { this.applyTranslate(); this.applyRotate(); this.applyScale(); } @SideOnly(Side.CLIENT) public void applyTranslate() { GL11.glTranslatef(this.translate[0], this.translate[1], this.translate[2]); } @SideOnly(Side.CLIENT) public void applyRotate() { GL11.glRotatef(this.rotate[2], 0, 0, 1); GL11.glRotatef(this.rotate[1], 0, 1, 0); GL11.glRotatef(this.rotate[0], 1, 0, 0); } @SideOnly(Side.CLIENT) public void applyScale() { GL11.glScalef(this.scale[0], this.scale[1], this.scale[2]); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("translate", this.translate).add("scale", this.scale).add("rotate", this.rotate).toString(); } public void interpolate(ModelTransform a, ModelTransform b, float x, Interpolation interp) { for (int i = 0; i < this.translate.length; i++) { this.translate[i] = interp.interpolate(a.translate[i], b.translate[i], x); this.scale[i] = interp.interpolate(a.scale[i], b.scale[i], x); this.rotate[i] = interp.interpolate(a.rotate[i], b.rotate[i], x); } } }
5,741
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLimb.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelLimb.java
package mchorse.blockbuster.api; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.MoreObjects; import com.google.gson.annotations.Expose; import mchorse.blockbuster.common.OrientedBB; import net.minecraft.inventory.EntityEquipmentSlot; /** * Limb class * * This class is responsible for holding data that describing the limb. * It contains meta data and data about visuals and game play. */ public class ModelLimb { /* OrientedBoundingBox */ public transient List<OrientedBB> obbs = new ArrayList<>(); /* Meta data */ public String name = ""; public String parent = ""; /* Visuals */ public int[] size = new int[] {4, 4, 4}; public float sizeOffset = 0; public float itemScale = 1; public int[] texture = new int[] {0, 0}; public float[] anchor = new float[] {0.5F, 0.5F, 0.5F}; public float[] color = new float[] {1.0F, 1.0F, 1.0F}; public float opacity = 1.0F; public boolean mirror; public boolean lighting = true; public boolean shading = true; public boolean smooth = false; public boolean is3D = false; /* Game play */ public Holding holding = Holding.NONE; public ArmorSlot slot = ArmorSlot.NONE; public boolean hold = true; public boolean swiping; public boolean lookX; public boolean lookY; public boolean swinging; public boolean idle; public boolean invert; public boolean wheel; public boolean wing; public boolean roll; public boolean cape; /* OBJ */ public float[] origin = new float[] {0F, 0F, 0F}; /* VOX */ public int specular = 0x00000000; public ModelLimb() {} public ModelLimb(String name) { this.name = name; } /** * Clone a model limb */ @Override public ModelLimb clone() { ModelLimb b = new ModelLimb(); if(!this.obbs.isEmpty()) { for(OrientedBB obb : this.obbs) { b.obbs.add(obb.clone()); } } b.name = this.name; b.parent = this.parent; b.size = new int[] {this.size[0], this.size[1], this.size[2]}; b.sizeOffset = this.sizeOffset; b.itemScale = this.itemScale; b.texture = new int[] {this.texture[0], this.texture[1]}; b.anchor = new float[] {this.anchor[0], this.anchor[1], this.anchor[2]}; b.color = new float[] {this.color[0], this.color[1], this.color[2]}; b.opacity = this.opacity; b.mirror = this.mirror; b.lighting = this.lighting; b.shading = this.shading; b.smooth = this.smooth; b.is3D = this.is3D; b.holding = this.holding; b.slot = this.slot; b.hold = this.hold; b.swiping = this.swiping; b.lookX = this.lookX; b.lookY = this.lookY; b.swinging = this.swinging; b.idle = this.idle; b.invert = this.invert; b.wheel = this.wheel; b.wing = this.wing; b.roll = this.roll; b.cape = this.cape; b.origin = new float[] {this.origin[0], this.origin[1], this.origin[2]}; b.specular = this.specular; return b; } @Override public String toString() { return MoreObjects.toStringHelper(this).add("parent", this.parent).add("size", Arrays.toString(this.size)).add("texture", Arrays.toString(this.texture)).add("anchor", Arrays.toString(this.anchor)).add("mirror", this.mirror).toString(); } public static enum Holding { NONE, RIGHT, LEFT; } /** * Armor slots */ public static enum ArmorSlot { NONE(null, "none"), HEAD(EntityEquipmentSlot.HEAD, "head"), CHEST(EntityEquipmentSlot.CHEST, "chest"), LEFT_SHOULDER(EntityEquipmentSlot.CHEST, "left_shoulder"), RIGHT_SHOULDER(EntityEquipmentSlot.CHEST, "right_shoulder"), LEGGINGS(EntityEquipmentSlot.LEGS, "leggings"), LEFT_LEG(EntityEquipmentSlot.LEGS, "left_leg"), RIGHT_LEG(EntityEquipmentSlot.LEGS, "right_leg"), LEFT_FOOT(EntityEquipmentSlot.FEET, "left_foot"), RIGHT_FOOT(EntityEquipmentSlot.FEET, "right_foot"); public final EntityEquipmentSlot slot; public final String name; public static ArmorSlot fromName(String str) { for (ArmorSlot slot : values()) { if (slot.name.equals(str)) return slot; } return NONE; } private ArmorSlot(EntityEquipmentSlot slot, String name) { this.slot = slot; this.name = name; } } }
4,641
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelClientHandler.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelClientHandler.java
package mchorse.blockbuster.api; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import mchorse.blockbuster.client.model.ModelCustom; import mchorse.blockbuster.client.model.parsing.ModelExtrudedLayer; import net.minecraft.client.Minecraft; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * Client-side model handler * * The difference between this class and its parent, is that this class * is also compiling {@link ModelCustom} out of added {@link Model}s, * and removes custom models from {@link ModelCustom#MODELS}. */ @SideOnly(Side.CLIENT) public class ModelClientHandler extends ModelHandler { @Override @SuppressWarnings("unchecked") public void addModel(String key, IModelLazyLoader loader) throws Exception { super.addModel(key, loader); ModelCustom.MODELS.put(key, loader.loadClientModel(key, this.models.get(key))); } @Override protected void addMorph(String key, Model model) { Blockbuster.proxy.factory.section.add(key, model, true); } @Override public void removeModel(String key) { super.removeModel(key); final ModelCustom model = ModelCustom.MODELS.remove(key); if (model == null) { return; } Minecraft.getMinecraft().addScheduledTask(() -> { /* If this gets run on the integrated server on the server * side, then it kicks the player due to state exception * because OpenGL operations must be done on the client * thread... * * Hopefully scheduling it fix this issue */ model.delete(); ModelExtrudedLayer.clearByModel(model); }); } }
1,847
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelPack.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/ModelPack.java
package mchorse.blockbuster.api; import com.google.common.collect.ImmutableList; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.api.loaders.IModelLoader; import mchorse.blockbuster.api.loaders.ModelLoaderJSON; import mchorse.blockbuster.api.loaders.ModelLoaderOBJ; import mchorse.blockbuster.api.loaders.ModelLoaderVOX; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderJSON; import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderOBJ; import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderVOX; import mchorse.blockbuster.api.resource.IResourceEntry; import mchorse.blockbuster.api.resource.StreamEntry; import mchorse.blockbuster.utils.mclib.ImageFolder; import net.minecraftforge.common.DimensionManager; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Model pack class */ public class ModelPack { /** * List of model loaders */ public List<IModelLoader> loaders = new ArrayList<IModelLoader>(); /** * Cached models */ public Map<String, IModelLazyLoader> models = new HashMap<String, IModelLazyLoader>(); /** * Folders which to check when reloading models */ public List<File> folders = new ArrayList<File>(); /** * Map for only changed models */ public Map<String, IModelLazyLoader> changed = new HashMap<String, IModelLazyLoader>(); /** * List of removed models */ public List<String> removed = new ArrayList<String>(); private long lastTime; private Map<String, ModelUserItem> packed = new HashMap<String, ModelUserItem>(); public ModelPack() { this.loaders.add(new ModelLoaderVOX()); this.loaders.add(new ModelLoaderOBJ()); this.loaders.add(new ModelLoaderJSON()); this.setupFolders(); this.setupPackedModels(); } private void setupPackedModels() { try { InputStream stream = this.getClass().getClassLoader().getResourceAsStream("assets/blockbuster/models/user.json"); String json = IOUtils.toString(stream, StandardCharsets.UTF_8); this.packed = new Gson().fromJson(json, new TypeToken<Map<String, ModelUserItem>>(){}.getType()); } catch (Exception e) {} } public IModelLazyLoader create(File file) { IModelLazyLoader lazyLoader = null; for (IModelLoader loader : this.loaders) { lazyLoader = loader.load(file); if (lazyLoader != null) { break; } } return lazyLoader; } /** * Setup folders */ public void setupFolders() { this.folders.clear(); this.addFolder(new ImageFolder(CommonProxy.configFile, "models")); if (Blockbuster.modelFolderPath != null && !Blockbuster.modelFolderPath.get().isEmpty()) { this.addFolder(new File(Blockbuster.modelFolderPath.get())); } File server = DimensionManager.getCurrentSaveRootDirectory(); if (server != null) { this.addFolder(new File(server, "blockbuster/models")); } } /** * Add a folder to the list of folders to where to look up models and skins */ private void addFolder(File folder) { folder.mkdirs(); if (folder.isDirectory()) { this.folders.add(folder); } } /** * Reload model handler */ public void reload() { this.setupFolders(); this.changed.clear(); this.removed.clear(); this.lastTime = System.currentTimeMillis(); for (File folder : this.folders) { this.reloadModels(folder, ""); } this.removeOld(); try { /* Load default provided models */ this.addDefaultModel("alex"); this.addDefaultModel("alex_3d"); this.addDefaultModel("steve"); this.addDefaultModel("steve_3d"); this.addDefaultModel("fred"); this.addDefaultModel("fred_3d"); this.addDefaultModel("empty"); this.addDefaultModel("cape"); /* Eyes related models */ List<String> shapes = ImmutableList.of( "eyebrow_l", "eyebrow_r", "eyelid_lb", "eyelid_lt", "eyelid_rb", "eyelid_rt" ); this.addDefaultModel("eyes/3.0"); this.addDefaultModel("eyes/3.0_1px"); this.addDefaultModelWithShapes("eyes/3.1", shapes); this.addDefaultModelWithShapes("eyes/3.1_simple", shapes); this.addDefaultModel("eyes/alex"); this.addDefaultModel("eyes/steve"); this.addDefaultModel("eyes/fred"); this.addDefaultModel("eyes/head"); this.addDefaultModel("eyes/head_3d"); /* Of course I know him, he's me */ this.addDefaultModel("mchorse/head"); if (this.packed != null) { for (Map.Entry<String, ModelUserItem> entry : this.packed.entrySet()) { this.addUserModel(entry.getKey(), entry.getValue()); } } } catch (Exception e) { e.printStackTrace(); } } private void addUserModel(String id, ModelUserItem userItem) { IModelLazyLoader lazy = this.models.get(id); if (lazy == null) { String path = "assets/blockbuster/models/user/" + id; ClassLoader loader = this.getClass().getClassLoader(); StreamEntry json = new StreamEntry(path + "/model.json", 0, loader); if (userItem.obj != null) { String mtlPath = userItem.mtl == null ? null : path + "/" + userItem.mtl; StreamEntry obj = new StreamEntry(path + "/" + userItem.obj, 0, loader); StreamEntry mtl = new StreamEntry(mtlPath, 0, loader); List<IResourceEntry> s = new ArrayList<IResourceEntry>(); if (userItem.shapes != null) { for (String shape : userItem.shapes) { s.add(new StreamEntry(path + "/" + shape, 0, loader)); } } lazy = new ModelLazyLoaderOBJ(json, obj, mtl, s); } else if (userItem.vox != null) { lazy = new ModelLazyLoaderVOX(json, new StreamEntry(path + "/" + userItem.vox, 0, loader)); } else { lazy = new ModelLazyLoaderJSON(json); } lazy.setLastTime(-1); this.models.put(id, lazy); this.changed.put(id, lazy); this.removed.remove(id); } } /** * Remove old entries */ private void removeOld() { Iterator<Map.Entry<String, IModelLazyLoader>> it = this.models.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, IModelLazyLoader> entry = it.next(); long lastTime = entry.getValue().getLastTime(); if (lastTime < this.lastTime && lastTime >= 0) { it.remove(); this.removed.add(entry.getKey()); } } } /** * Add a default model bundled with the mod */ private void addDefaultModel(String id) throws Exception { IModelLazyLoader lazy = this.models.get(id); if (lazy == null) { String path = "assets/blockbuster/models/entity/"; ClassLoader loader = this.getClass().getClassLoader(); lazy = new ModelLazyLoaderJSON(new StreamEntry(path + id + ".json", 0, loader)); lazy.setLastTime(-1); this.models.put(id, lazy); this.changed.put(id, lazy); this.removed.remove(id); } } private void addDefaultModelWithShapes(String id, List<String> shapes) throws Exception { IModelLazyLoader lazy = this.models.get(id); if (lazy == null) { String path = "assets/blockbuster/models/entity/"; ClassLoader loader = this.getClass().getClassLoader(); StreamEntry json = new StreamEntry(path + id + ".json", 0, loader); StreamEntry obj = new StreamEntry(path + id + "/base.obj", 0, loader); List<IResourceEntry> s = new ArrayList<IResourceEntry>(); for (String shape : shapes) { s.add(new StreamEntry(path + id + "/" + shape + ".obj", 0, loader)); } lazy = new ModelLazyLoaderOBJ(json, obj, new StreamEntry(null, 0, loader), s); lazy.setLastTime(-1); this.models.put(id, lazy); this.changed.put(id, lazy); this.removed.remove(id); } } /** * Reload models * * Simply caches files in the map */ protected void reloadModels(File folder, String prefix) { for (File file : folder.listFiles()) { String name = file.getName(); if (name.startsWith("__") || name.equals("skins") || file.isFile() || (name.equals("particles") && prefix.isEmpty())) { continue; } String path = prefix + name; IModelLazyLoader lazyLoader = this.models.get(path); if (lazyLoader != null && lazyLoader.getLastTime() >= 0) { if (lazyLoader.stillExists()) { lazyLoader.setLastTime(this.lastTime); if (lazyLoader.hasChanged()) { this.changed.put(path, lazyLoader); } continue; } } else { /* Overwriting the default model */ lazyLoader = null; } for (IModelLoader loader : this.loaders) { lazyLoader = loader.load(file); if (lazyLoader != null) { lazyLoader.setLastTime(this.lastTime); break; } } if (lazyLoader != null) { this.models.put(path, lazyLoader); this.changed.put(path, lazyLoader); } else { this.reloadModels(file, path + "/"); } } } }
11,102
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelPoseAdapter.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/json/ModelPoseAdapter.java
package mchorse.blockbuster.api.json; import java.lang.reflect.Type; import java.util.Map; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import mchorse.blockbuster.api.ModelPose; import mchorse.blockbuster.api.ModelTransform; /** * Model limb adapter */ public class ModelPoseAdapter implements JsonSerializer<ModelPose> { @Override public JsonElement serialize(ModelPose src, Type typeOfSrc, JsonSerializationContext context) { JsonElement serial = ModelAdapter.plainGSON.toJsonTree(src, typeOfSrc); JsonObject map = serial.getAsJsonObject(); JsonObject limbs = new JsonObject(); map.remove("limbs"); if (src.shapes.isEmpty()) { map.remove("shapes"); } for (Map.Entry<String, ModelTransform> limb : src.limbs.entrySet()) { ModelTransform trans = limb.getValue(); JsonObject transform = new JsonObject(); boolean empty = true; if (!isDefault(trans.translate, 0)) { addFloatArray(transform, "translate", trans.translate); empty = false; } if (!isDefault(trans.rotate, 0)) { addFloatArray(transform, "rotate", trans.rotate); empty = false; } if (!isDefault(trans.scale, 1)) { addFloatArray(transform, "scale", trans.scale); empty = false; } if (!empty) { limbs.add(limb.getKey(), transform); } } map.add("limbs", limbs); return map; } public static boolean isDefault(float[] array, float defaultValue) { return array[0] == defaultValue && array[1] == defaultValue && array[2] == defaultValue; } public static void addFloatArray(JsonObject map, String name, float[] array) { JsonArray jsonArray = new JsonArray(); for (float num : array) { jsonArray.add(new JsonPrimitive(num)); } map.add(name, jsonArray); } }
2,311
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLimbAdapter.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/json/ModelLimbAdapter.java
package mchorse.blockbuster.api.json; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.vecmath.Matrix3d; import com.google.gson.JsonArray; 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.JsonSerializationContext; import com.google.gson.JsonSerializer; import mchorse.blockbuster.api.ModelLimb; import mchorse.blockbuster.api.ModelLimb.ArmorSlot; import mchorse.blockbuster.api.ModelLimb.Holding; import mchorse.blockbuster.common.OrientedBB; /** * Model limb adapter */ public class ModelLimbAdapter implements JsonSerializer<ModelLimb>, JsonDeserializer<ModelLimb> { @Override public JsonElement serialize(ModelLimb src, Type typeOfSrc, JsonSerializationContext context) { JsonElement serial = ModelAdapter.plainGSON.toJsonTree(src, typeOfSrc); JsonObject map = serial.getAsJsonObject(); map.remove("sizeOffset"); map.remove("itemScale"); map.remove("holding"); map.remove("slot"); map.remove("parent"); map.remove("name"); map.remove("opacity"); map.remove("color"); if(!src.obbs.isEmpty()) { JsonArray jsonOBBs = new JsonArray(); for(OrientedBB obb : src.obbs) { JsonObject jsonOBB = new JsonObject(); JsonArray size = new JsonArray(); size.add(obb.hw * 32D); size.add(obb.hu * 32D); size.add(obb.hv * 32D); jsonOBB.add("size", size); if(obb.anchorOffset.x != 0 || obb.anchorOffset.y != 0 || obb.anchorOffset.z != 0) { JsonArray anchor = new JsonArray(); anchor.add(obb.anchorOffset.x * 16D); anchor.add(obb.anchorOffset.y * 16D); anchor.add(obb.anchorOffset.z * 16D); jsonOBB.add("anchor", anchor); } if(obb.limbOffset.x != 0 || obb.limbOffset.y != 0 || obb.limbOffset.z != 0) { JsonArray translate = new JsonArray(); translate.add(obb.limbOffset.x * 16D); translate.add(obb.limbOffset.y * 16D); translate.add(obb.limbOffset.z * 16D); jsonOBB.add("translate", translate); } if(obb.rotation0[0] != 0 || obb.rotation0[1] != 0 || obb.rotation0[2] != 0) { JsonArray rotation = new JsonArray(); rotation.add(obb.rotation0[0]); rotation.add(obb.rotation0[1]); rotation.add(obb.rotation0[2]); jsonOBB.add("rotate", rotation); } jsonOBBs.add(jsonOBB); } map.add("orientedBBs", jsonOBBs); } if (src.sizeOffset != 0) { map.addProperty("sizeOffset", src.sizeOffset); } if (src.itemScale != 1F) { map.addProperty("itemScale", src.itemScale); } if (src.holding != Holding.NONE) { map.addProperty("holding", src.holding == Holding.RIGHT ? "right" : "left"); } if (src.slot != null && src.slot != ArmorSlot.NONE) { map.addProperty("slot", src.slot.name); } if (!src.parent.isEmpty()) { map.addProperty("parent", src.parent); } if (!ModelPoseAdapter.isDefault(src.color, 1.0F)) { ModelPoseAdapter.addFloatArray(map, "color", src.color); } if (src.opacity != 1.0F) { map.addProperty("opacity", src.opacity); } this.addBoolean(map, "lighting", src.lighting, true); this.addBoolean(map, "shading", src.shading, true); this.addBoolean(map, "smooth", src.smooth, false); this.addBoolean(map, "is3D", src.is3D, false); this.addBoolean(map, "hold", src.hold, true); this.addBoolean(map, "mirror", src.mirror, false); this.addBoolean(map, "lookX", src.lookX, false); this.addBoolean(map, "lookY", src.lookY, false); this.addBoolean(map, "idle", src.idle, false); this.addBoolean(map, "swinging", src.swinging, false); this.addBoolean(map, "swiping", src.swiping, false); this.addBoolean(map, "invert", src.invert, false); this.addBoolean(map, "wheel", src.wheel, false); this.addBoolean(map, "wing", src.wing, false); this.addBoolean(map, "roll", src.roll, false); this.addBoolean(map, "cape", src.cape, false); if (!ModelPoseAdapter.isDefault(src.origin, 0F)) { ModelPoseAdapter.addFloatArray(map, "origin", src.origin); } return map; } @Override public ModelLimb deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { ModelLimb limb = ModelAdapter.plainGSON.fromJson(json, ModelLimb.class); JsonObject object = json.getAsJsonObject(); if(object.has("orientedBBs")) { JsonArray obbs = object.getAsJsonArray("orientedBBs"); for(JsonElement element : obbs) { JsonObject jsonOBB = element.getAsJsonObject(); OrientedBB obb = new OrientedBB(); if(jsonOBB.has("size")) { obb.hw = jsonOBB.getAsJsonArray("size").get(0).getAsDouble() / 32D; obb.hu = jsonOBB.getAsJsonArray("size").get(1).getAsDouble() / 32D; obb.hv = jsonOBB.getAsJsonArray("size").get(2).getAsDouble() / 32D; } if(jsonOBB.has("anchor")) { obb.anchorOffset.x = jsonOBB.getAsJsonArray("anchor").get(0).getAsDouble() / 16D; obb.anchorOffset.y = jsonOBB.getAsJsonArray("anchor").get(1).getAsDouble() / 16D; obb.anchorOffset.z = jsonOBB.getAsJsonArray("anchor").get(2).getAsDouble() / 16D; } if(jsonOBB.has("translate")) { obb.limbOffset.x = jsonOBB.getAsJsonArray("translate").get(0).getAsDouble() / 16D; obb.limbOffset.y = jsonOBB.getAsJsonArray("translate").get(1).getAsDouble() / 16D; obb.limbOffset.z = jsonOBB.getAsJsonArray("translate").get(2).getAsDouble() / 16D; } if(jsonOBB.has("rotate")) { obb.rotation0[0] = jsonOBB.getAsJsonArray("rotate").get(0).getAsDouble(); obb.rotation0[1] = jsonOBB.getAsJsonArray("rotate").get(1).getAsDouble(); obb.rotation0[2] = jsonOBB.getAsJsonArray("rotate").get(2).getAsDouble(); } limb.obbs.add(obb); } } if (object.has("looking") && object.get("looking").isJsonPrimitive()) { boolean looking = object.get("looking").getAsBoolean(); limb.lookX = limb.lookY = looking; } if (object.has("holding") && object.get("holding").isJsonPrimitive()) { String holding = object.get("holding").getAsString(); if (holding.equals("right")) { limb.holding = Holding.RIGHT; } else if (holding.equals("left")) { limb.holding = Holding.LEFT; } } if (limb.holding == null) { limb.holding = Holding.NONE; } if (object.has("slot")) { try { limb.slot = ArmorSlot.fromName(object.get("slot").getAsString()); } catch (Exception e) {} } else { limb.slot = ArmorSlot.NONE; } return limb; } /** * Add a boolean to the map * * First remove the property from map, and then, if the given value isn't * the default one, add the value */ private void addBoolean(JsonObject map, String name, boolean value, boolean defaultValue) { map.remove(name); if (value != defaultValue) { map.addProperty(name, value); } } }
8,935
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelAdapter.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/json/ModelAdapter.java
package mchorse.blockbuster.api.json; import java.lang.reflect.Type; import java.util.Map; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; 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.api.Model; import mchorse.blockbuster.api.ModelLimb; import mchorse.mclib.utils.resources.RLUtils; import net.minecraft.util.ResourceLocation; /** * Model JSON adapter * * This adapter is responsible for only deserializing a {@link Model} instance. */ public class ModelAdapter implements JsonDeserializer<Model>, JsonSerializer<Model> { public static Gson plainGSON = new GsonBuilder().create(); /** * Deserializes {@link Model} * * This method is responsible mainly from translating "default" field into * {@link ResourceLocation}. */ @Override public Model deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Model model = plainGSON.fromJson(json, Model.class); JsonObject object = json.getAsJsonObject(); model.shapes.clear(); if (object.has("limbs")) { model.limbs = context.deserialize(object.get("limbs"), new TypeToken<Map<String, ModelLimb>>() {}.getType()); } if (object.has("default")) { model.defaultTexture = RLUtils.create(object.get("default")); } if (model.extrudeMaxFactor <= 0) { model.extrudeMaxFactor = 1; } if (model.extrudeInwards <= 0) { model.extrudeInwards = 1; } return model; } /** * Serializes {@link Model} * * This method is responsible for cleaning up some of Model's fields (to * make the file output more cleaner). */ @Override public JsonElement serialize(Model src, Type typeOfSrc, JsonSerializationContext context) { JsonElement serial = plainGSON.toJsonTree(src, typeOfSrc); JsonObject map = serial.getAsJsonObject(); map.remove("model"); map.remove("defaultTexture"); map.remove("skins"); map.remove("scale"); map.remove("scaleGui"); map.remove("limbs"); map.remove("poses"); map.remove("providesObj"); map.remove("providesMtl"); map.remove("legacyObj"); map.remove("materials"); map.remove("shapes"); map.remove("extrudeMaxFactor"); map.remove("extrudeInwards"); if (src.presets.isEmpty()) { map.remove("presets"); } if (!src.model.isEmpty()) { map.addProperty("model", src.model); } if (src.defaultTexture != null) { map.add("default", RLUtils.writeJson(src.defaultTexture)); } if (!src.skins.isEmpty()) { map.addProperty("skins", src.skins); } if (src.scale[0] != 1 || src.scale[1] != 1 || src.scale[2] != 1) { JsonArray array = new JsonArray(); array.add(new JsonPrimitive(src.scale[0])); array.add(new JsonPrimitive(src.scale[1])); array.add(new JsonPrimitive(src.scale[2])); map.add("scale", array); } if (src.scaleGui != 1) { map.addProperty("scaleGui", src.scaleGui); } if (src.providesObj) { map.addProperty("providesObj", src.providesObj); } if (src.providesMtl) { map.addProperty("providesMtl", src.providesMtl); } if (!src.skins.isEmpty()) { map.addProperty("skins", src.skins); } if (src.extrudeMaxFactor > 1) { map.addProperty("extrudeMaxFactor", src.extrudeMaxFactor); } if (src.extrudeInwards > 1) { map.addProperty("extrudeInwards", src.extrudeInwards); } if (!src.legacyObj) { map.addProperty("legacyObj", src.legacyObj); } map.add("limbs", context.serialize(src.limbs)); map.add("poses", context.serialize(src.poses)); return map; } }
4,592
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Mesh.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/Mesh.java
package mchorse.blockbuster.api.formats; /** * Holds the mesh data */ public class Mesh { public float[] posData; public float[] texData; public float[] normData; public int triangles; public Mesh(int triangles) { this(new float[triangles * 9], new float[triangles * 6], new float[triangles * 9]); } public Mesh(float[] posData, float[] texData, float[] normData) { this.posData = posData; this.texData = texData; this.normData = normData; this.triangles = posData.length / 3; } }
567
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
IMeshes.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/IMeshes.java
package mchorse.blockbuster.api.formats; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.ModelLimb; import mchorse.blockbuster.api.ModelTransform; import mchorse.blockbuster.client.model.ModelCustom; import mchorse.blockbuster.client.model.ModelCustomRenderer; import javax.vecmath.Vector3f; public interface IMeshes { public ModelCustomRenderer createRenderer(Model data, ModelCustom model, ModelLimb limb, ModelTransform transform); public Vector3f getMin(); public Vector3f getMax(); }
526
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxReader.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/VoxReader.java
package mchorse.blockbuster.api.formats.vox; import mchorse.blockbuster.api.formats.vox.data.Vox; import mchorse.blockbuster.api.formats.vox.data.VoxChunk; import mchorse.blockbuster.api.formats.vox.data.VoxGroup; import mchorse.blockbuster.api.formats.vox.data.VoxLayer; import mchorse.blockbuster.api.formats.vox.data.VoxShape; import mchorse.blockbuster.api.formats.vox.data.VoxTransform; import mchorse.mclib.utils.binary.BinaryReader; import javax.vecmath.Matrix3f; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** * MagicaVoxel *.vox reader * * This class reads the file and returns vox model * * @link https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox.txt * @link https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox-extension.txt */ public class VoxReader extends BinaryReader { public static int[] DEFAULT_PALETTE = new int[] {0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff, 0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff, 0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc, 0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc, 0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99, 0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699, 0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66, 0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666, 0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066, 0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933, 0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033, 0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00, 0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300, 0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044, 0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000, 0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111}; public byte[] buf = new byte[4]; public VoxDocument read(InputStream stream) throws Exception { if (this.readInt(stream) != this.fourChars("VOX ")) { throw new Exception("Not a 'VOX ' file!"); } int version = this.readInt(stream); if (version != 150) { System.out.println("Reading a vox file with version: " + version + ". This version might not be supported. Version 150 is supported."); } VoxChunk main = this.readChunk(stream); if (!main.id.equals("MAIN")) { throw new Exception("The first chunk isn't main!"); } VoxDocument document = new VoxDocument(); Vox vox = null; while (true) { VoxChunk chunk; try { chunk = this.readChunk(stream); } catch (Exception e) { break; } /* System.out.println(chunk.toString() + " " + chunk.size + " " + chunk.chunks); */ if (chunk.id.equals("SIZE")) { vox = new Vox(); vox.x = this.readInt(stream); vox.z = this.readInt(stream); vox.y = this.readInt(stream); } else if (chunk.id.equals("XYZI")) { int voxels = this.readInt(stream); vox.voxels = new int[vox.x * vox.z * vox.y]; while (voxels > 0) { stream.read(this.buf); int x = this.buf[0] & 0xff; int y = this.buf[2] & 0xff; int z = this.buf[1] & 0xff; int block = this.buf[3] & 0xff; vox.set(x, y, z, block); voxels--; } document.chunks.add(vox); } else if (chunk.id.equals("nTRN")) { document.nodes.add(new VoxTransform(stream, this)); } else if (chunk.id.equals("nGRP")) { document.nodes.add(new VoxGroup(stream, this)); } else if (chunk.id.equals("nSHP")) { document.nodes.add(new VoxShape(stream, this)); } else if (chunk.id.equals("LAYR")) { document.layers.add(new VoxLayer(stream, this)); } else if (chunk.id.equals("RGBA")) { document.palette = new int[256]; for (int i = 0; i <= 254; i++) { int color = this.readInt(stream); int newColor = (((color >> 24) & 0xff) << 24); newColor += (((color >> 0) & 0xff) << 16); newColor += (((color >> 8) & 0xff) << 8); newColor += (((color >> 16) & 0xff) << 0); document.palette[i + 1] = newColor; } } else { stream.skip(chunk.size); } } stream.close(); return document; } public VoxChunk readChunk(InputStream stream) throws Exception { return new VoxChunk(this.readFourString(stream), this.readInt(stream), this.readInt(stream)); } public String readString(InputStream stream) throws Exception { int size = this.readInt(stream); byte[] bytes = new byte[size]; if (stream.read(bytes) == size) { return new String(bytes, StandardCharsets.UTF_8); } throw new IOException("Not enough bytes for the string!"); } public Map<String, String> readDictionary(InputStream stream) throws Exception { Map<String, String> dict = new HashMap<String, String>(); int keys = this.readInt(stream); for (int i = 0; i < keys; i ++) { dict.put(this.readString(stream), this.readString(stream)); } return dict; } public Matrix3f readRotation(int rotation) { Matrix3f matrix = new Matrix3f(); int firstIndex = (rotation & 0b0011); int secondIndex = (rotation & 0b1100) >> 2; int[] array = {-1, -1, -1}; int index = 0; array[firstIndex] = 0; array[secondIndex] = 0; for (int i = 0; i < array.length; i ++) { if (array[i] == -1) { index = i; break; } } int thirdIndex = index; boolean negativeFirst = ((rotation & 0b0010000) >> 4) == 1; boolean negativeSecond = ((rotation & 0b0100000) >> 5) == 1; boolean negativeThird = ((rotation & 0b1000000) >> 6) == 1; matrix.setElement(0, firstIndex, negativeFirst ? -1 : 1); matrix.setElement(1, secondIndex, negativeSecond ? -1 : 1); matrix.setElement(2, thirdIndex, negativeThird ? -1 : 1); return matrix; } }
9,152
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
MeshesVOX.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/MeshesVOX.java
package mchorse.blockbuster.api.formats.vox; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.ModelLimb; import mchorse.blockbuster.api.ModelTransform; import mchorse.blockbuster.api.formats.IMeshes; import mchorse.blockbuster.api.formats.Mesh; import mchorse.blockbuster.api.formats.vox.data.Vox; import mchorse.blockbuster.client.model.ModelCustom; import mchorse.blockbuster.client.model.ModelCustomRenderer; import mchorse.blockbuster.client.model.ModelVoxRenderer; import javax.vecmath.Matrix3f; import javax.vecmath.Vector3f; public class MeshesVOX implements IMeshes { public Mesh mesh; public VoxDocument document; public Vox vox; public Matrix3f rotation; public MeshesVOX(VoxDocument document, VoxDocument.LimbNode node) { this.document = document; this.vox = node.chunk; this.rotation = node.rotation; } @Override public ModelCustomRenderer createRenderer(Model data, ModelCustom model, ModelLimb limb, ModelTransform transform) { if (this.mesh == null) { this.mesh = new VoxBuilder(this.rotation).build(this.vox); } return new ModelVoxRenderer(model, limb, transform, this); } @Override public Vector3f getMin() { Vector3f min = new Vector3f(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); for (int x = 0; x < this.vox.x; x++) { for (int y = 0; y < this.vox.y; y++) { for (int z = 0; z < this.vox.z; z++) { if (this.vox.has(x, y, z)) { min.x = Math.min(x, min.x); min.y = Math.min(y, min.y); min.z = Math.min(z, min.z); } } } } return min; } @Override public Vector3f getMax() { Vector3f max = new Vector3f(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); for (int x = 0; x < this.vox.x; x++) { for (int y = 0; y < this.vox.y; y++) { for (int z = 0; z < this.vox.z; z++) { if (this.vox.has(x, y, z)) { max.x = Math.max(x, max.x); max.y = Math.max(y, max.y); max.z = Math.max(z, max.z); } } } } return max; } }
2,564
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxBuilder.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/VoxBuilder.java
package mchorse.blockbuster.api.formats.vox; import mchorse.blockbuster.api.formats.Mesh; import mchorse.blockbuster.api.formats.vox.data.Vox; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.vecmath.Matrix3f; import javax.vecmath.Vector3f; @SideOnly(Side.CLIENT) public class VoxBuilder { public Matrix3f transform; public Vector3f vector = new Vector3f(); private Vector3f right; private Vector3f left; private Vector3f front; private Vector3f back; private Vector3f bottom; private Vector3f top; public VoxBuilder(Matrix3f transform) { this.transform = transform; this.right = this.processNormal(new Vector3f(-1, 0, 0)); this.left = this.processNormal(new Vector3f(1, 0, 0)); this.front = this.processNormal(new Vector3f(0, 0, 1)); this.back = this.processNormal(new Vector3f(0, 0, -1)); this.bottom = this.processNormal(new Vector3f(0, -1, 0)); this.top = this.processNormal(new Vector3f(0, 1, 0)); } private Vector3f processNormal(Vector3f normal) { /* Transform the normal */ normal.set(normal.x, normal.z, normal.y); this.transform.transform(normal); normal.set(normal.x, normal.z, normal.y); normal.normalize(); return normal; } public Mesh build(Vox vox) { /* Worst case scenario */ Mesh mesh = new Mesh(vox.blocks * 12); mesh.triangles = 0; for (int x = 0; x < vox.x; x++) { for (int y = 0; y < vox.y; y++) { for (int z = 0; z < vox.z; z++) { int voxel = vox.voxels[vox.toIndex(x, y, z)]; if (voxel != 0) { this.buildVertex(mesh, x, y, z, voxel, vox); } } } } return mesh; } private void buildVertex(Mesh mesh, int x, int y, int z, int voxel, Vox vox) { boolean top = vox.has(x, y + 1, z); boolean bottom = vox.has(x, y - 1, z); boolean left = vox.has(x + 1, y, z); boolean right = vox.has(x - 1, y, z); boolean front = vox.has(x, y, z + 1); boolean back = vox.has(x, y, z - 1); if (!top) { Vector3f normal = this.top; this.add(mesh, vox, x, y + 1, z, voxel, -0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x, y + 1, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x, y + 1, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z + 1, voxel, 0.5F, 0.5F, normal); } if (!bottom) { Vector3f normal = this.bottom; this.add(mesh, vox, x, y, z, voxel, -0.5F, -0.5F, normal); this.add(mesh, vox, x, y, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x, y, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y, z + 1, voxel, 0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y, z, voxel, 0.5F, -0.5F, normal); } if (!left) { Vector3f normal = this.left; this.add(mesh, vox, x + 1, y, z, voxel, -0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z + 1, voxel, 0.5F, 0.5F, normal); } if (!right) { Vector3f normal = this.right; this.add(mesh, vox, x, y, z, voxel, -0.5F, -0.5F, normal); this.add(mesh, vox, x, y + 1, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x, y, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x, y + 1, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x, y + 1, z + 1, voxel, 0.5F, 0.5F, normal); this.add(mesh, vox, x, y, z + 1, voxel, -0.5F, 0.5F, normal); } if (!front) { Vector3f normal = this.front; this.add(mesh, vox, x, y, z + 1, voxel, -0.5F, -0.5F, normal); this.add(mesh, vox, x, y + 1, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y, z + 1, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x, y + 1, z + 1, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z + 1, voxel, 0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y, z + 1, voxel, 0.5F, -0.5F, normal); } if (!back) { Vector3f normal = this.back; this.add(mesh, vox, x, y, z, voxel, -0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x, y + 1, z, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x, y + 1, z, voxel, -0.5F, 0.5F, normal); this.add(mesh, vox, x + 1, y, z, voxel, 0.5F, -0.5F, normal); this.add(mesh, vox, x + 1, y + 1, z, voxel, 0.5F, 0.5F, normal); } } private void add(Mesh mesh, Vox vox, int x, int y, int z, int voxel, float offsetU, float offsetV, Vector3f normal) { int tris = mesh.triangles; float u = (voxel + 0.5F + offsetU) / 256F; float v = 0.5F + offsetV; Vector3f vertex = this.process(x, y, z, vox); mesh.posData[tris * 3] = vertex.x; mesh.posData[tris * 3 + 1] = vertex.y; mesh.posData[tris * 3 + 2] = vertex.z; mesh.normData[tris * 3] = normal.x; mesh.normData[tris * 3 + 1] = normal.y; mesh.normData[tris * 3 + 2] = normal.z; mesh.texData[tris * 2] = u; mesh.texData[tris * 2 + 1] = v; mesh.triangles += 1; } private Vector3f process(int x, int y, int z, Vox vox) { int w = (int) (vox.x / 2F); int h = (int) (vox.y / 2F); int d = (int) (vox.z / 2F); this.vector.set(x - w, z - d, y - h); this.transform.transform(this.vector); this.vector.set(this.vector.x, this.vector.z, this.vector.y); return this.vector; } }
6,644
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxDocument.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/VoxDocument.java
package mchorse.blockbuster.api.formats.vox; import mchorse.blockbuster.api.formats.vox.data.Vox; import mchorse.blockbuster.api.formats.vox.data.VoxBaseNode; import mchorse.blockbuster.api.formats.vox.data.VoxGroup; import mchorse.blockbuster.api.formats.vox.data.VoxLayer; import mchorse.blockbuster.api.formats.vox.data.VoxShape; import mchorse.blockbuster.api.formats.vox.data.VoxTransform; import javax.vecmath.Matrix3f; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class VoxDocument { /** * RGBA palette */ public int[] palette = VoxReader.DEFAULT_PALETTE; /** * List of all chunks */ public List<Vox> chunks = new ArrayList<Vox>(); /** * Nodes */ public List<VoxBaseNode> nodes = new ArrayList<VoxBaseNode>(); /** * Nodes */ public List<VoxLayer> layers = new ArrayList<VoxLayer>(); private int index; /** * Generate a list of nodes for easier limb generation */ public List<LimbNode> generate() { List<LimbNode> nodes = new ArrayList<LimbNode>(); Stack<Matrix3f> matStack = new Stack<Matrix3f>(); Stack<Vector3f> vecStack = new Stack<Vector3f>(); this.index = 0; if (this.nodes.size() == 0) { /* Legacy mode */ Matrix3f identity = new Matrix3f(); identity.setIdentity(); for (Vox chunk : this.chunks) { Vector3f position = new Vector3f(0, 0, (chunk.z - 1) / 2); nodes.add(new LimbNode(chunk, identity, position, this.index == 0 ? "vox" : "vox_" + this.index)); this.index ++; } } else { this.generateNodes((VoxTransform) this.nodes.get(0), nodes, matStack, vecStack); } return nodes; } private void generateNodes(VoxTransform transform, List<LimbNode> nodes, Stack<Matrix3f> matStack, Stack<Vector3f> vecStack) { VoxBaseNode child = this.nodes.get(transform.childId); String name = "vox_" + this.index; boolean hidden = transform.attrs.containsKey("_hidden") && transform.attrs.get("_hidden").equals("1"); if (!hidden && transform.layerId < this.layers.size() && transform.layerId >= 0) { hidden = this.layers.get(transform.layerId).isHidden(); } if (transform.attrs.containsKey("_name")) { name = transform.attrs.get("_name") + "_" + this.index; } Matrix3f parentMat; Vector3f parentVec; Matrix4f trans = transform.transforms.get(0); if (matStack.isEmpty()) { parentMat = new Matrix3f(); parentMat.m00 = trans.m00; parentMat.m01 = trans.m01; parentMat.m02 = trans.m02; parentMat.m10 = trans.m10; parentMat.m11 = trans.m11; parentMat.m12 = trans.m12; parentMat.m20 = trans.m20; parentMat.m21 = trans.m21; parentMat.m22 = trans.m22; parentVec = new Vector3f(trans.m03, trans.m13, trans.m23); } else { parentMat = new Matrix3f(matStack.peek()); parentVec = new Vector3f(vecStack.peek()); Matrix3f mat = new Matrix3f(); mat.m00 = trans.m00; mat.m01 = trans.m01; mat.m02 = trans.m02; mat.m10 = trans.m10; mat.m11 = trans.m11; mat.m12 = trans.m12; mat.m20 = trans.m20; mat.m21 = trans.m21; mat.m22 = trans.m22; parentMat.mul(mat); parentVec.add(new Vector3f(trans.m03, trans.m13, trans.m23)); } matStack.push(parentMat); vecStack.push(parentVec); if (child instanceof VoxGroup) { VoxGroup group = (VoxGroup) child; for (int id : group.ids) { this.index += 1; this.generateNodes((VoxTransform) this.nodes.get(id), nodes, matStack, vecStack); } } else if (child instanceof VoxShape) { Matrix3f mat = matStack.pop(); Vector3f vec = vecStack.pop(); if (!hidden) { Vox chunk = this.chunks.get(((VoxShape) child).modelAttrs.get(0).id); nodes.add(new LimbNode(chunk, mat, vec, name)); } } } public static class LimbNode { public Vox chunk; public Matrix3f rotation; public Vector3f translation; public String name; public LimbNode(Vox chunk, Matrix3f rotation, Vector3f translation, String name) { this.chunk = chunk; this.rotation = rotation; this.translation = translation; this.name = name; } } }
4,978
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxBaseNode.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxBaseNode.java
package mchorse.blockbuster.api.formats.vox.data; import java.util.Map; public abstract class VoxBaseNode { public int id; public Map<String, String> attrs; public int num; }
188
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxChunk.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxChunk.java
package mchorse.blockbuster.api.formats.vox.data; import mchorse.mclib.utils.binary.BinaryChunk; /** * This represents a data chunk information in the VOX file * (not used anywhere outside of vox reader class) */ public class VoxChunk extends BinaryChunk { public int chunks; public VoxChunk(String id, int size, int chunks) { super(id, size); this.chunks = chunks; } @Override public String toString() { return this.id; } }
489
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxLayer.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxLayer.java
package mchorse.blockbuster.api.formats.vox.data; import mchorse.blockbuster.api.formats.vox.VoxReader; import java.io.InputStream; public class VoxLayer extends VoxBaseNode { public VoxLayer(InputStream stream, VoxReader reader) throws Exception { this.id = reader.readInt(stream); this.attrs = reader.readDictionary(stream); this.num = reader.readInt(stream); } public boolean isHidden() { return this.attrs.containsKey("_hidden") && this.attrs.get("_hidden").equals("1"); } }
538
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxGroup.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxGroup.java
package mchorse.blockbuster.api.formats.vox.data; import mchorse.blockbuster.api.formats.vox.VoxReader; import java.io.InputStream; public class VoxGroup extends VoxBaseNode { public int[] ids; public VoxGroup(InputStream stream, VoxReader reader) throws Exception { this.id = reader.readInt(stream); this.attrs = reader.readDictionary(stream); this.num = reader.readInt(stream); this.ids = new int[this.num]; for (int i = 0; i < num; i ++) { this.ids[i] = reader.readInt(stream); } } }
576
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Vox.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/Vox.java
package mchorse.blockbuster.api.formats.vox.data; public class Vox { public int x; public int y; public int z; public int blocks; public int[] voxels; public int toIndex(int x, int y, int z) { return x + y * this.x + z * this.x * this.y; } public boolean has(int x, int y, int z) { return x >= 0 && y >= 0 && z >= 0 && x < this.x && y < this.y && z < this.z && this.voxels[this.toIndex(x, y, z)] != 0; } public void set(int x, int y, int z, int block) { int index = this.toIndex(x, y, z); if (index < 0 || index >= this.x * this.y * this.z) { return; } int last = this.voxels[index]; this.voxels[index] = block; if (last == 0 && block != 0) { this.blocks += 1; } else if (last != 0 && block == 0) { this.blocks -= 1; } } }
935
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxTransform.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxTransform.java
package mchorse.blockbuster.api.formats.vox.data; import mchorse.blockbuster.api.formats.vox.VoxReader; import javax.vecmath.Matrix3f; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; public class VoxTransform extends VoxBaseNode { public int childId; public int unusedId; public int layerId; public List<Matrix4f> transforms; public VoxTransform(InputStream stream, VoxReader reader) throws Exception { this.id = reader.readInt(stream); this.attrs = reader.readDictionary(stream); this.childId = reader.readInt(stream); this.unusedId = reader.readInt(stream); this.layerId = reader.readInt(stream); this.num = reader.readInt(stream); this.transforms = new ArrayList<Matrix4f>(); for (int i = 0; i < this.num; i ++) { Map<String, String> dict = reader.readDictionary(stream); Matrix3f rotation = new Matrix3f(); Vector3f translate = new Vector3f(0, 0, 0); rotation.setIdentity(); if (dict.containsKey("_r")) { rotation = reader.readRotation(Integer.parseInt(dict.get("_r"))); } if (dict.containsKey("_t")) { String[] splits = dict.get("_t").split(" "); if (splits.length == 3) { /* Stupid coordinate systems... */ translate.set(-Integer.parseInt(splits[0]), Integer.parseInt(splits[1]), Integer.parseInt(splits[2])); } } /* Assemble the main result */ Matrix4f transform = new Matrix4f(); transform.set(rotation); transform.setTranslation(translate); this.transforms.add(transform); } } }
1,922
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxShape.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxShape.java
package mchorse.blockbuster.api.formats.vox.data; import mchorse.blockbuster.api.formats.vox.VoxReader; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; public class VoxShape extends VoxBaseNode { public List<Attribute> modelAttrs; public VoxShape(InputStream stream, VoxReader reader) throws Exception { this.id = reader.readInt(stream); this.attrs = reader.readDictionary(stream); this.num = reader.readInt(stream); this.modelAttrs = new ArrayList<Attribute>(); for (int i = 0; i < this.num; i ++) { this.modelAttrs.add(new Attribute(reader.readInt(stream), reader.readDictionary(stream))); } } public static class Attribute { public final int id; public final Map<String, String> attrs; public Attribute(int id, Map<String, String> attrs) { this.id = id; this.attrs = attrs; } } }
1,002
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
VoxTexture.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/vox/data/VoxTexture.java
package mchorse.blockbuster.api.formats.vox.data; import java.util.Arrays; import net.minecraft.client.renderer.texture.DynamicTexture; public class VoxTexture extends DynamicTexture { private int[] palette; private int specular; public VoxTexture(int[] palette, int specular) { super(Math.max(palette.length, 1), 1); this.palette = palette; this.specular = specular; this.updatePalette(); } public void updatePalette() { int[] tex = this.getTextureData(); for (int i = 0; i < this.palette.length; i++) { tex[i] = this.palette[i]; } if (tex.length == 3 * this.palette.length) { Arrays.fill(tex, 2 * this.palette.length, tex.length, specular); } this.updateDynamicTexture(); } }
839
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ShapeKey.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/ShapeKey.java
package mchorse.blockbuster.api.formats.obj; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import java.util.Objects; public class ShapeKey { public String name; public float value; public boolean relative = true; public ShapeKey() {} public ShapeKey(String name, float value) { this.name = name; this.value = value; } public ShapeKey(String name, float value, boolean relative) { this(name, value); this.relative = relative; } public ShapeKey setValue(float value) { this.value = value; return this; } @Override public boolean equals(Object obj) { if (obj instanceof ShapeKey) { ShapeKey shape = (ShapeKey) obj; return this.value == shape.value && Objects.equals(this.name, shape.name) && this.relative == shape.relative; } return super.equals(obj); } public ShapeKey copy() { return new ShapeKey(this.name, this.value, this.relative); } public NBTBase toNBT() { NBTTagCompound tag = new NBTTagCompound(); tag.setString("Name", this.name); tag.setFloat("Value", this.value); tag.setBoolean("Relative", this.relative); return tag; } public void fromNBT(NBTTagCompound key) { this.name = key.getString("Name"); this.value = key.getFloat("Value"); this.relative = key.getBoolean("Relative"); } }
1,521
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Vector2f.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/Vector2f.java
package mchorse.blockbuster.api.formats.obj; /** * Substitute class for a 2d vector which comes with joml library */ public class Vector2f { public float x; public float y; public Vector2f(float x, float y) { this.x = x; this.y = y; } }
276
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
OBJDataMesh.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/OBJDataMesh.java
package mchorse.blockbuster.api.formats.obj; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Mesh from OBJ file * * It holds faces for every object found in OBJ file */ public class OBJDataMesh { public String name; public Map<OBJMaterial, List<OBJFace>> groups = new LinkedHashMap<OBJMaterial, List<OBJFace>>(); }
364
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
OBJMaterial.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/OBJMaterial.java
package mchorse.blockbuster.api.formats.obj; import net.minecraft.util.ResourceLocation; /** * OBJ material * * This class stores information about OBJ material from MTL file */ public class OBJMaterial { public String name; public float r = 1; public float g = 1; public float b = 1; public boolean useTexture; public boolean linear = false; public ResourceLocation texture; public OBJMaterial(String name) { this.name = name; } }
489
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
MeshesOBJ.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/MeshesOBJ.java
package mchorse.blockbuster.api.formats.obj; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.ModelLimb; 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.blockbuster.client.model.ModelOBJRenderer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MeshesOBJ implements IMeshes { public List<MeshOBJ> meshes = new ArrayList<MeshOBJ>(); public Map<String, List<MeshOBJ>> shapes; public ModelCustomRenderer createRenderer(Model data, ModelCustom model, ModelLimb limb, ModelTransform transform) { if (!data.providesObj) { return null; } return new ModelOBJRenderer(model, limb, transform, this); } public void mergeShape(String name, MeshesOBJ shape) { this.shapes = this.shapes == null ? new HashMap<String, List<MeshOBJ>>() : this.shapes; this.shapes.put(name, shape.meshes); } @Override public javax.vecmath.Vector3f getMin() { javax.vecmath.Vector3f min = new javax.vecmath.Vector3f(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); for (MeshOBJ obj : this.meshes) { for (int i = 0, c = obj.posData.length / 3; i < c; i++) { min.x = Math.min(obj.posData[i * 3], min.x); min.y = Math.min(obj.posData[i * 3 + 1], min.y); min.z = Math.min(obj.posData[i * 3 + 2], min.z); } } return min; } @Override public javax.vecmath.Vector3f getMax() { javax.vecmath.Vector3f max = new javax.vecmath.Vector3f(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); for (MeshOBJ obj : this.meshes) { for (int i = 0, c = obj.posData.length / 3; i < c; i++) { max.x = Math.max(obj.posData[i * 3], max.x); max.y = Math.max(obj.posData[i * 3 + 1], max.y); max.z = Math.max(obj.posData[i * 3 + 2], max.z); } } return max; } }
2,291
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
OBJFace.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/OBJFace.java
package mchorse.blockbuster.api.formats.obj; /** * Face that holds indices for loading data */ class OBJFace { /** * List of idxGroup groups for a face triangle (3 vertices per face). */ public OBJIndexGroup[] idxGroups = new OBJIndexGroup[3]; public OBJFace(String[] lines) { for (int i = 0; i < 3; i++) { this.idxGroups[i] = this.parseLine(lines[i]); } } /** * Parse index group from a string in format of "1/2/3". It can be also * "1//3" if the model doesn't provides texture coordinates. */ private OBJIndexGroup parseLine(String line) { OBJIndexGroup idxGroup = new OBJIndexGroup(); String[] lineTokens = line.split("/"); int length = lineTokens.length; idxGroup.idxPos = Integer.parseInt(lineTokens[0]) - 1; if (length > 1) { /* It can be empty if the obj does not define text coords */ String textCoord = lineTokens[1]; if (!textCoord.isEmpty()) { idxGroup.idxTextCoord = Integer.parseInt(textCoord) - 1; } if (length > 2) { idxGroup.idxVecNormal = Integer.parseInt(lineTokens[2]) - 1; } } return idxGroup; } }
1,317
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
OBJParser.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/OBJParser.java
package mchorse.blockbuster.api.formats.obj; import mchorse.blockbuster.api.formats.IMeshes; import mchorse.blockbuster.api.formats.Mesh; import mchorse.mclib.commands.SubCommandBase; import mchorse.mclib.utils.resources.RLUtils; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * OBJ and MTL parser and loader */ public class OBJParser { /* Input files */ public InputStream objFile; public InputStream mtlFile; /* Collected data */ public List<Vector3f> vertices = new ArrayList<Vector3f>(); public List<Vector2f> textures = new ArrayList<Vector2f>(); public List<Vector3f> normals = new ArrayList<Vector3f>(); public List<OBJDataMesh> objects = new ArrayList<OBJDataMesh>(); public Map<String, OBJMaterial> materials = new HashMap<String, OBJMaterial>(); public static String processMaterialName(String name) { /* Apparently material name can have slashes and backslashes, so * they must be replaced to avoid messing up texture paths... */ return name.replaceAll("[/|\\\\]+", "-"); } /** * Read all lines from a file (needs a text file) */ public static List<String> readAllLines(InputStream stream) throws Exception { List<String> list = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); String line; while ((line = br.readLine()) != null) { list.add(line); } br.close(); } catch (Exception e) { e.printStackTrace(); } return list; } /** * Construct OBJ parser with OBJ and MTL file references */ public OBJParser(InputStream objFile, InputStream mtlFile) { this.objFile = objFile; this.mtlFile = mtlFile; } public boolean equalData(OBJParser parser) { boolean result = this.vertices.size() == parser.vertices.size(); result = result && this.textures.size() == parser.textures.size(); result = result && this.normals.size() == parser.normals.size(); result = result && this.objects.size() == parser.objects.size(); here: for (OBJDataMesh mesh : this.objects) { for (OBJDataMesh dataMesh : parser.objects) { if (mesh.name.equals(dataMesh.name)) { result = result && mesh.groups.size() == dataMesh.groups.size(); continue here; } } return false; } return result; } /** * Read the data first */ public void read() throws Exception { this.vertices.clear(); this.textures.clear(); this.normals.clear(); this.objects.clear(); this.materials.clear(); this.readMTL(); this.readOBJ(); } /** * Setup material textures */ public void setupTextures(String key, File folder) { /* Create a texture location for materials */ for (OBJMaterial material : this.materials.values()) { if (material.useTexture && material.texture == null) { material.texture = RLUtils.create("b.a", key + "/skins/" + material.name + "/default.png"); /* Create folder for every material */ new File(folder, "skins/" + material.name + "/").mkdirs(); } } } /** * Read materials from MTL file. This method isn't necessarily will * read any materials because MTL file is optional */ public void readMTL() throws Exception { if (this.mtlFile == null) { return; } List<String> lines = readAllLines(this.mtlFile); OBJMaterial material = null; for (String line : lines) { if (line.isEmpty()) { continue; } String[] tokens = line.split("\\s+"); String first = tokens[0]; if (first.equals("newmtl")) { material = new OBJMaterial(processMaterialName(tokens[1])); this.materials.put(material.name, material); } /* Read diffuse color */ else if (first.equals("Kd") && tokens.length == 4) { material.r = Float.parseFloat(tokens[1]); material.g = Float.parseFloat(tokens[2]); material.b = Float.parseFloat(tokens[3]); } /* Read texture */ else if (first.equals("map_Kd")) { material.useTexture = true; } else if (first.equals("map_Kd_linear")) { material.linear = true; } else if (first.equals("map_Kd_path")) { String texture = String.join(" ", SubCommandBase.dropFirstArgument(tokens)); material.texture = RLUtils.create(texture); } } } /** * Read objects from OBJ file */ public void readOBJ() throws Exception { List<String> lines = readAllLines(this.objFile); OBJDataMesh mesh = null; OBJMaterial material = null; for (String line : lines) { String[] tokens = line.split("\\s+"); String first = tokens[0]; /* Blender uses "o" for objects, while C4D uses "g" */ if ((first.equals("o") || first.equals("g")) && tokens.length >= 2) { String name = tokens[1]; mesh = null; for (OBJDataMesh data : this.objects) { if (data.name.equals(name)) { mesh = data; break; } } if (mesh == null) { mesh = new OBJDataMesh(); mesh.name = name; this.objects.add(mesh); } } /* Vertices */ if (first.equals("v")) { this.vertices.add(new Vector3f(Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]), Float.parseFloat(tokens[3]))); } /* Texture coordinates (UV) */ else if (first.equals("vt")) { this.textures.add(new Vector2f(Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]))); } /* Who needs normals? */ else if (first.equals("vn")) { this.normals.add(new Vector3f(Float.parseFloat(tokens[1]), Float.parseFloat(tokens[2]), Float.parseFloat(tokens[3]))); } /* Material group */ else if (first.equals("usemtl")) { material = this.materials.get(processMaterialName(tokens[1])); } /* Collect faces */ else if (first.equals("f")) { List<OBJFace> faceList = mesh.groups.get(material); if (faceList == null) { faceList = new ArrayList<OBJFace>(); mesh.groups.put(material, faceList); } String[] faces = SubCommandBase.dropFirstArgument(tokens); if (faces.length == 4) { /* Support for quads, yay! */ faceList.add(new OBJFace(new String[] {faces[0], faces[1], faces[2]})); faceList.add(new OBJFace(new String[] {faces[0], faces[2], faces[3]})); } else if (faces.length == 3) { faceList.add(new OBJFace(faces)); } else if (faces.length > 4) { for (int i = 0, c = faces.length - 2; i < c; i++) { faceList.add(new OBJFace(new String[] {faces[0], faces[i + 1], faces[i + 2]})); } } } } } /** * From collected information, form mesh data */ public Map<String, IMeshes> compile() { Map<String, IMeshes> meshes = new HashMap<String, IMeshes>(); for (OBJDataMesh obj : this.objects) { MeshesOBJ meshObject = new MeshesOBJ(); for (Map.Entry<OBJMaterial, List<OBJFace>> group : obj.groups.entrySet()) { List<OBJFace> faces = group.getValue(); MeshOBJ mesh = new MeshOBJ(faces.size()); int i = 0; for (OBJFace face : faces) { for (OBJIndexGroup indexGroup : face.idxGroups) { processFaceVertex(i, indexGroup, mesh); i++; } } mesh.material = group.getKey(); meshObject.meshes.add(mesh); } meshes.put(obj.name, meshObject); } return meshes; } /** * Place all the data to complementary arrays */ private void processFaceVertex(int i, OBJIndexGroup indices, Mesh mesh) { if (indices.idxPos >= 0) { Vector3f vertex = this.vertices.get(indices.idxPos); mesh.posData[i * 3] = vertex.x; mesh.posData[i * 3 + 1] = vertex.y; mesh.posData[i * 3 + 2] = vertex.z; } if (indices.idxTextCoord >= 0) { Vector2f coord = this.textures.get(indices.idxTextCoord); mesh.texData[i * 2] = coord.x; mesh.texData[i * 2 + 1] = 1 - coord.y; } if (indices.idxVecNormal >= 0) { Vector3f normal = this.normals.get(indices.idxVecNormal); mesh.normData[i * 3] = normal.x; mesh.normData[i * 3 + 1] = normal.y; mesh.normData[i * 3 + 2] = normal.z; } } }
10,446
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
OBJIndexGroup.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/OBJIndexGroup.java
package mchorse.blockbuster.api.formats.obj; /** * Index group class * * This class represents an index group. Used in {@link OBJFace} class to * represent an index group for looking up vertices from the collected * arrays. */ class OBJIndexGroup { public static final int NO_VALUE = -1; public int idxPos = NO_VALUE; public int idxTextCoord = NO_VALUE; public int idxVecNormal = NO_VALUE; }
419
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
MeshOBJ.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/MeshOBJ.java
package mchorse.blockbuster.api.formats.obj; import mchorse.blockbuster.api.formats.Mesh; public class MeshOBJ extends Mesh { public OBJMaterial material; public MeshOBJ(int faces) { super(faces); } public MeshOBJ(float[] posData, float[] texData, float[] normData) { super(posData, texData, normData); } }
354
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Vector3f.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/formats/obj/Vector3f.java
package mchorse.blockbuster.api.formats.obj; /** * Substitute class for a 3d vector which comes with joml library */ public class Vector3f { public float x; public float y; public float z; public Vector3f(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } }
326
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLoaderJSON.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/ModelLoaderJSON.java
package mchorse.blockbuster.api.loaders; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderJSON; import mchorse.blockbuster.api.resource.FileEntry; import java.io.File; public class ModelLoaderJSON implements IModelLoader { @Override public IModelLazyLoader load(File folder) { File file = new File(folder, "model.json"); if (file.isFile()) { return new ModelLazyLoaderJSON(new FileEntry(file)); } return null; } }
559
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLoaderOBJ.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/ModelLoaderOBJ.java
package mchorse.blockbuster.api.loaders; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderOBJ; import mchorse.blockbuster.api.resource.FileEntry; import mchorse.blockbuster.api.resource.IResourceEntry; import java.io.File; public class ModelLoaderOBJ implements IModelLoader { @Override public IModelLazyLoader load(File folder) { IResourceEntry json = new FileEntry(new File(folder, "model.json")); File obj = new File(folder, "model.obj"); File shapes = new File(folder, "shapes"); if (obj.isFile()) { File mtl = new File(folder, "model.mtl"); return new ModelLazyLoaderOBJ(json, new FileEntry(obj), new FileEntry(mtl), shapes); } for (File file : folder.listFiles()) { if (file.isFile() && file.getName().endsWith(".obj")) { String name = file.getName(); File mtl = new File(folder, name.substring(0, name.length() - 3) + "mtl"); return new ModelLazyLoaderOBJ(json, new FileEntry(file), new FileEntry(mtl), shapes); } } return null; } }
1,223
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
IModelLoader.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/IModelLoader.java
package mchorse.blockbuster.api.loaders; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import java.io.File; /** * Model loader interface * * Detects whether a special model format can be loaded */ public interface IModelLoader { public IModelLazyLoader load(File folder); }
300
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLoaderVOX.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/ModelLoaderVOX.java
package mchorse.blockbuster.api.loaders; import mchorse.blockbuster.api.loaders.lazy.IModelLazyLoader; import mchorse.blockbuster.api.loaders.lazy.ModelLazyLoaderVOX; import mchorse.blockbuster.api.resource.FileEntry; import mchorse.blockbuster.api.resource.IResourceEntry; import java.io.File; public class ModelLoaderVOX implements IModelLoader { @Override public IModelLazyLoader load(File folder) { IResourceEntry json = new FileEntry(new File(folder, "model.json")); File vox = new File(folder, "model.vox"); if (vox.isFile()) { return new ModelLazyLoaderVOX(json, new FileEntry(vox)); } for (File file : folder.listFiles()) { if (file.isFile() && file.getName().endsWith(".vox")) { return new ModelLazyLoaderVOX(json, new FileEntry(file)); } } return null; } }
924
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLazyLoaderJSON.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/lazy/ModelLazyLoaderJSON.java
package mchorse.blockbuster.api.loaders.lazy; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.formats.IMeshes; import mchorse.blockbuster.api.formats.obj.MeshesOBJ; import mchorse.blockbuster.api.resource.FileEntry; import mchorse.blockbuster.api.resource.IResourceEntry; import mchorse.blockbuster.client.model.ModelCustom; import mchorse.blockbuster.client.model.parsing.ModelExtrudedLayer; import mchorse.blockbuster.client.model.parsing.ModelParser; import net.minecraft.client.Minecraft; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.Map; public class ModelLazyLoaderJSON implements IModelLazyLoader { public IResourceEntry model; public long lastTime; public int lastCount = -1; public ModelLazyLoaderJSON(IResourceEntry model) { this.model = model; } public int count() { return this.model.exists() ? 1 : 0; } @Override public long getLastTime() { return this.lastTime; } @Override public void setLastTime(long lastTime) { if (this.lastCount == -1) { this.lastCount = this.count(); } this.lastTime = lastTime; } @Override public boolean stillExists() { return this.lastCount == this.count(); } @Override public boolean hasChanged() { return this.model.hasChanged(); } @Override public Model loadModel(String key) throws Exception { if (!this.model.exists()) { return null; } return Model.parse(this.model.getStream()); } @Override @SideOnly(Side.CLIENT) public ModelCustom loadClientModel(String key, Model model) throws Exception { /* GC the old model */ ModelCustom modelCustom = ModelCustom.MODELS.get(key); Minecraft.getMinecraft().addScheduledTask(() -> ModelExtrudedLayer.clearByModel(modelCustom)); Map<String, IMeshes> meshes = this.getMeshes(key, model); if (meshes != null) { for (String limb : meshes.keySet()) { if (!model.limbs.containsKey(limb)) { model.addLimb(limb); } } } if (!model.model.isEmpty()) { try { Class<? extends ModelCustom> clazz = (Class<? extends ModelCustom>) Class.forName(model.model); /* Parse custom custom model with a custom class */ return ModelParser.parse(key, model, clazz, meshes); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return ModelParser.parse(key, model, meshes); } @SideOnly(Side.CLIENT) protected Map<String, IMeshes> getMeshes(String key, Model model) throws Exception { return null; } @Override public boolean copyFiles(File folder) { if (this.model instanceof FileEntry) { FileEntry file = (FileEntry) this.model; if (!file.file.getParentFile().equals(folder)) { try { FileUtils.copyDirectory(new File(file.file.getParentFile(), "skins"), new File(folder, "skins")); return true; } catch (IOException e) { return false; } } } return true; } }
3,703
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
IModelLazyLoader.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/lazy/IModelLazyLoader.java
package mchorse.blockbuster.api.loaders.lazy; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.client.model.ModelCustom; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.File; import java.io.IOException; /** * Lazy model loader * * This class is actually responsible for creation of {@link Model} * or client side {@link ModelCustom} classes */ public interface IModelLazyLoader { public long getLastTime(); public void setLastTime(long time); public boolean stillExists(); public boolean hasChanged(); public boolean copyFiles(File folder); public Model loadModel(String key) throws Exception; @SideOnly(Side.CLIENT) public ModelCustom loadClientModel(String key, Model model) throws Exception; }
823
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLazyLoaderVOX.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/lazy/ModelLazyLoaderVOX.java
package mchorse.blockbuster.api.loaders.lazy; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.ModelLimb; import mchorse.blockbuster.api.ModelPose; import mchorse.blockbuster.api.ModelTransform; import mchorse.blockbuster.api.formats.IMeshes; import mchorse.blockbuster.api.formats.vox.MeshesVOX; import mchorse.blockbuster.api.formats.vox.VoxDocument; import mchorse.blockbuster.api.formats.vox.VoxReader; import mchorse.blockbuster.api.resource.IResourceEntry; import mchorse.blockbuster.client.model.ModelCustom; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.File; import java.util.HashMap; import java.util.Map; public class ModelLazyLoaderVOX extends ModelLazyLoaderJSON { public IResourceEntry vox; private VoxDocument cachedDocument; public ModelLazyLoaderVOX(IResourceEntry model, IResourceEntry vox) { super(model); this.vox = vox; } @Override public int count() { return super.count() + (this.vox.exists() ? 2 : 0); } @Override public boolean hasChanged() { return super.hasChanged() || this.vox.hasChanged(); } @Override public Model loadModel(String key) throws Exception { Model model = null; try { model = super.loadModel(key); } catch (Exception e) {} if (model == null) { model = this.generateVOXModel(key); } return model; } @Override @SideOnly(Side.CLIENT) protected Map<String, IMeshes> getMeshes(String key, Model model) throws Exception { Map<String, IMeshes> meshes = new HashMap<String, IMeshes>(); VoxDocument document = this.getVox(); for (VoxDocument.LimbNode node : document.generate()) { meshes.put(node.name, new MeshesVOX(document, node)); } return meshes; } @Override @SideOnly(Side.CLIENT) public ModelCustom loadClientModel(String key, Model model) throws Exception { ModelCustom custom = super.loadClientModel(key, model); this.cachedDocument = null; return custom; } /** * Generate custom model based on given VOX */ private Model generateVOXModel(String model) throws Exception { /* Generate custom model for a VOX model */ Model data = new Model(); ModelPose blocky = new ModelPose(); /* Generate limbs */ VoxDocument document = this.getVox(); for (VoxDocument.LimbNode node : document.generate()) { ModelLimb limb = data.addLimb(node.name); ModelTransform transform = new ModelTransform(); limb.origin[0] = 0; limb.origin[1] = 0; limb.origin[2] = 0; transform.translate[0] = -node.translation.x; transform.translate[1] = node.translation.z; transform.translate[2] = -node.translation.y; blocky.limbs.put(limb.name, transform); } /* General model properties */ data.providesObj = true; data.providesMtl = true; blocky.setSize(1, 1, 1); data.poses.put("flying", blocky.copy()); data.poses.put("standing", blocky.copy()); data.poses.put("sneaking", blocky.copy()); data.poses.put("sleeping", blocky.copy()); data.poses.put("riding", blocky.copy()); data.name = model; return data; } private VoxDocument getVox() throws Exception { if (this.cachedDocument != null) { return this.cachedDocument; } return this.cachedDocument = new VoxReader().read(this.vox.getStream()); } @Override public boolean copyFiles(File folder) { boolean skins = super.copyFiles(folder); boolean vox = this.vox.copyTo(new File(folder, this.vox.getName())); return skins || vox; } }
4,010
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ModelLazyLoaderOBJ.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/loaders/lazy/ModelLazyLoaderOBJ.java
package mchorse.blockbuster.api.loaders.lazy; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.ModelPose; import mchorse.blockbuster.api.formats.IMeshes; import mchorse.blockbuster.api.formats.obj.MeshesOBJ; import mchorse.blockbuster.api.formats.obj.OBJDataMesh; import mchorse.blockbuster.api.formats.obj.OBJParser; import mchorse.blockbuster.api.resource.FileEntry; import mchorse.blockbuster.api.resource.IResourceEntry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ModelLazyLoaderOBJ extends ModelLazyLoaderJSON { public IResourceEntry obj; public IResourceEntry mtl; public List<IResourceEntry> shapes = new ArrayList<IResourceEntry>(); private OBJParser parser; private long lastModified = -1; private File shapesFolder; public ModelLazyLoaderOBJ(IResourceEntry model, IResourceEntry obj, IResourceEntry mtl, List<IResourceEntry> shapes) { super(model); this.obj = obj; this.mtl = mtl; this.shapes.addAll(shapes); } public ModelLazyLoaderOBJ(IResourceEntry model, IResourceEntry obj, IResourceEntry mtl, File shapes) { super(model); this.obj = obj; this.mtl = mtl; this.setupShapes(shapes); } private void setupShapes(File shapes) { if (shapes == null) { return; } File[] files = shapes.listFiles(); if (files == null) { return; } this.shapesFolder = shapes; for (File file : files) { if (file.isFile() && file.getName().endsWith(".obj")) { this.shapes.add(new FileEntry(file)); } } } @Override public int count() { int count = super.count() + (this.obj.exists() ? 2 : 0) + (this.mtl.exists() ? 4 : 0); int bit = 3; for (IResourceEntry shape : this.shapes) { if (shape.exists()) { count += shape.exists() ? 1 << bit : 0; } bit++; } return count; } @Override public boolean hasChanged() { boolean hasChanged = super.hasChanged() || this.obj.hasChanged() || this.mtl.hasChanged(); for (IResourceEntry shape : this.shapes) { hasChanged = hasChanged || shape.hasChanged(); } File[] files = this.shapesFolder == null ? null : this.shapesFolder.listFiles(); if (files != null) { boolean haveShapesChanged = this.hasShapesFolderChanged(files); /* Update shapes */ if (haveShapesChanged) { if (this.shapesFolder != null) { this.setupShapes(this.shapesFolder); } this.lastModified = -1; this.parser = null; } hasChanged = hasChanged || haveShapesChanged; } return hasChanged; } private boolean hasShapesFolderChanged(File[] files) { int matching = 0; int total = 0; for (File file : files) { String name = file.getName(); if (name.endsWith(".obj")) { total += 1; } for (IResourceEntry entry : this.shapes) { if (entry.getName().equals(name)) { matching += 1; break; } } } return matching != total; } @Override public Model loadModel(String key) throws Exception { Model model = null; try { model = super.loadModel(key); } catch (Exception e) {} if (model == null) { model = this.generateOBJModel(key); } for (IResourceEntry entry : this.shapes) { if (!entry.exists()) { continue; } String name = entry.getName(); name = name.substring(0, name.lastIndexOf(".")); model.shapes.add(name); } return model; } @Override @SideOnly(Side.CLIENT) protected Map<String, IMeshes> getMeshes(String key, Model model) throws Exception { try { OBJParser parser = this.getOBJParser(key, model); Map<String, IMeshes> meshes = parser.compile(); for (IResourceEntry shape : this.shapes) { try { OBJParser shapeParser = new OBJParser(shape.getStream(), model.providesMtl ? this.mtl.getStream() : null); shapeParser.read(); this.mergeParsers(shape.getName(), meshes, shapeParser); } catch (Exception e) {} } this.parser = null; this.lastModified = -1; return meshes; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Merges data of shape parsers */ private void mergeParsers(String name, Map<String, IMeshes> meshes, OBJParser shapeParser) { name = name.substring(0, name.lastIndexOf(".")); Map<String, IMeshes> shapeMeshes = shapeParser.compile(); for (Map.Entry<String, IMeshes> entry : meshes.entrySet()) { IMeshes shapeMesh = shapeMeshes.get(entry.getKey()); if (shapeMesh != null) { ((MeshesOBJ) entry.getValue()).mergeShape(name, (MeshesOBJ) shapeMesh); } } } /** * Create an OBJ parser */ public OBJParser getOBJParser(String key, Model model) { if (!model.providesObj) { return null; } long lastModified = Math.max(this.model.lastModified(), Math.max(this.obj.lastModified(), this.mtl.lastModified())); if (this.lastModified < lastModified) { this.lastModified = lastModified; } else { return this.parser; } try { InputStream obj = this.obj.getStream(); InputStream mtl = model.providesMtl ? this.mtl.getStream() : null; this.parser = new OBJParser(obj, mtl); this.parser.read(); if (this.mtl instanceof FileEntry) { this.parser.setupTextures(key, ((FileEntry) this.mtl).file.getParentFile()); } model.materials.putAll(this.parser.materials); } catch (Exception e) { e.printStackTrace(); return null; } return this.parser; } /** * Generate custom model based on given OBJ */ private Model generateOBJModel(String model) { /* Generate custom model for an OBJ model */ Model data = new Model(); ModelPose blocky = new ModelPose(); blocky.setSize(1, 1, 1); data.poses.put("flying", blocky.copy()); data.poses.put("standing", blocky.copy()); data.poses.put("sneaking", blocky.copy()); data.poses.put("sleeping", blocky.copy()); data.poses.put("riding", blocky.copy()); data.name = model; data.providesObj = true; data.providesMtl = this.mtl.exists(); /* Generate limbs */ OBJParser parser = this.getOBJParser(model, data); if (parser != null) { for (OBJDataMesh mesh : parser.objects) { data.addLimb(mesh.name); } } if (data.limbs.isEmpty()) { data.addLimb("body"); } data.legacyObj = false; return data; } @Override public boolean copyFiles(File folder) { boolean result = super.copyFiles(folder); result = this.obj.copyTo(new File(folder, this.obj.getName())) || result; result = this.mtl.copyTo(new File(folder, this.mtl.getName())) || result; for (IResourceEntry shape : this.shapes) { result = shape.copyTo(new File(folder, "shapes/" + shape.getName())) || result; } return result; } }
8,565
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
StreamEntry.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/resource/StreamEntry.java
package mchorse.blockbuster.api.resource; import mchorse.blockbuster.Blockbuster; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; public class StreamEntry implements IResourceEntry { public String path; public long time; public ClassLoader loader = Blockbuster.class.getClassLoader(); public StreamEntry(String path, long time) { this.path = path; this.time = time; } @Override public String getName() { return this.path == null ? "" : FilenameUtils.getName(this.path); } public StreamEntry(String path, long time, ClassLoader loader) { this(path, time); this.loader = loader; } @Override public InputStream getStream() throws IOException { return this.path == null ? null : this.loader.getResourceAsStream(this.path); } @Override public boolean exists() { return this.path != null && this.loader.getResource(this.path) != null; } @Override public boolean hasChanged() { return false; } @Override public long lastModified() { return this.time; } @Override public boolean copyTo(File file) { try { FileUtils.copyInputStreamToFile(this.getStream(), file); return true; } catch (IOException e) {} return false; } }
1,515
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
IResourceEntry.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/resource/IResourceEntry.java
package mchorse.blockbuster.api.resource; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * Resource entry * * Used for the model system to allow both file based stream creation * and just stream creation via class loader/inside of jar */ public interface IResourceEntry { public String getName(); public static IResourceEntry createEntry(Object object) { if (object instanceof File) { return new FileEntry((File) object); } else if (object instanceof String) { return new StreamEntry((String) object, System.currentTimeMillis()); } return new StreamEntry(null, 0); } public InputStream getStream() throws IOException; public boolean exists(); public boolean hasChanged(); public long lastModified(); public boolean copyTo(File file); }
900
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
FileEntry.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/api/resource/FileEntry.java
package mchorse.blockbuster.api.resource; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class FileEntry implements IResourceEntry { public File file; public long lastModified; public FileEntry(File file) { this.file = file; this.lastModified = this.lastModified(); } @Override public String getName() { return this.file == null ? "" : this.file.getName(); } @Override public InputStream getStream() throws IOException { return this.file == null ? null : new FileInputStream(this.file); } @Override public boolean exists() { return this.file != null && this.file.exists(); } @Override public boolean hasChanged() { long lastModified = this.lastModified(); boolean result = lastModified > this.lastModified; this.lastModified = lastModified; return result; } @Override public long lastModified() { return this.file == null ? 0 : this.file.lastModified(); } @Override public boolean copyTo(File file) { try { FileUtils.copyFile(this.file, file); return true; } catch (IOException e) {} return false; } }
1,393
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
PlayerHandler.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/events/PlayerHandler.java
package mchorse.blockbuster.events; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.client.RenderingHandler; import mchorse.blockbuster.client.SkinHandler; import mchorse.blockbuster.client.render.tileentity.TileEntityGunItemStackRenderer; import mchorse.blockbuster.client.render.tileentity.TileEntityModelItemStackRenderer; import mchorse.blockbuster.client.textures.GifTexture; import mchorse.blockbuster.common.GunProps; import mchorse.blockbuster.common.item.ItemGun; import mchorse.blockbuster.recording.scene.Scene; import mchorse.blockbuster.utils.NBTUtils; import mchorse.blockbuster_pack.morphs.StructureMorph; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumActionResult; import net.minecraft.util.NonNullList; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; 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.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Iterator; import java.util.Map; import java.util.function.Function; /** * \* User: Evanechecssss * \* https://evanechecssss.github.io * \ */ public class PlayerHandler { private Function<GunProps, Boolean> leftHandler = (props) -> props.preventLeftClick; private Function<GunProps, Boolean> rightHandler = (props) -> props.preventRightClick; private Function<GunProps, Boolean> attackHandler = (props) -> props.preventEntityAttack; private int timer; private int skinsTimer; private static NonNullList<ItemStack> mainInventoryBefore = NonNullList.withSize(36, ItemStack.EMPTY); @SubscribeEvent(priority = EventPriority.HIGHEST) public void onLivingAttack(LivingAttackEvent event) { Entity source = event.getSource().getTrueSource(); if (source instanceof EntityPlayer) { this.handle((EntityPlayer) source, event, attackHandler); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent.LeftClickBlock event) { this.handle(event.getEntityPlayer(), event, leftHandler); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent.EntityInteract event) { this.handle(event.getEntityPlayer(), event, rightHandler); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent.RightClickBlock event) { this.handle(event.getEntityPlayer(), event, rightHandler); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent.RightClickItem event) { this.handle(event.getEntityPlayer(), event, rightHandler); } private static void preventItemPickUpScenePlayback(InventoryPlayer inventoryPlayer) { for (Map.Entry<String, Scene> scene : CommonProxy.scenes.getScenes().entrySet()) { for (EntityPlayer player : scene.getValue().getTargetPlaybackPlayers()) { if (player.inventory == inventoryPlayer) { preventItemPickUp(player); } } } } /** * Reset the inventory to what it was before the item was picked up. * This also absorbs the dropped item */ public static void preventItemPickUp(EntityPlayer player) { for (int i = 0; i < player.inventory.mainInventory.size(); i++) { ItemStack itemStackNow = player.inventory.mainInventory.get(i); ItemStack itemStackBefore = mainInventoryBefore.get(i); if (!ItemStack.areItemStacksEqual(itemStackNow, itemStackBefore)) { player.inventory.mainInventory.set(i, itemStackBefore); } } } /** * Called by ASM {@link mchorse.blockbuster.core.transformers.EntityItemTransformer} * before item pick up event is fired and before the item is added to the inventory * @param entity * @param itemStack */ public static void beforePlayerItemPickUp(EntityPlayer entity, ItemStack itemStack) { } /** * Called by ASM {@link mchorse.blockbuster.core.transformers.InventoryPlayerTransformer} * before an item is added to inventory in {@link InventoryPlayer} * @param inventory the inventory where this method is called from */ public static void beforeItemStackAdd(InventoryPlayer inventory) { for (int i = 0; i < inventory.mainInventory.size(); i++) { ItemStack copy = inventory.mainInventory.get(i).copy(); mainInventoryBefore.set(i, copy); } } /** * Called by ASM {@link mchorse.blockbuster.core.transformers.InventoryPlayerTransformer} * after an item is added to inventory in {@link InventoryPlayer} * @param inventory the inventory where this method is called from */ public static void afterItemStackAdd(InventoryPlayer inventory) { preventItemPickUpScenePlayback(inventory); } private void handle(EntityPlayer player, LivingEvent event, Function<GunProps, Boolean> handler) { ItemStack stack = player.getHeldItemMainhand(); if (!(stack.getItem() instanceof ItemGun)) { return; } GunProps props = NBTUtils.getGunProps(stack); if (props == null) { return; } if (handler.apply(props) && event.isCancelable()) { event.setCanceled(true); if (event instanceof PlayerInteractEvent) { ((PlayerInteractEvent) event).setCancellationResult(EnumActionResult.FAIL); } } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onPlayerTick(TickEvent.PlayerTickEvent event) { if (event.phase == Phase.END) { /* Update TEs in the model's TEISR */ if (event.player.world.isRemote) { /* * The PlayerTickEvent is called for every player on a server. * Only update the client once per tick. */ if (Minecraft.getMinecraft().player == event.player) { this.updateClient(); } } else { if (this.timer % 100 == 0) { StructureMorph.checkStructures(); this.timer = 0; } this.timer += 1; } return; } EntityPlayer player = event.player; ItemStack stack = player.getHeldItemMainhand(); if (stack.getItem() instanceof ItemGun) { ItemGun.decreaseReload(stack, player); ItemGun.decreaseTime(stack, player); ItemGun.checkGunState(stack, player); ItemGun.checkGunReload(stack, player); } } @SideOnly(Side.CLIENT) private void updateClient() { /* model blocks item update */ Iterator<Map.Entry<NBTTagCompound, TileEntityModelItemStackRenderer.TEModel>> iter0 = TileEntityModelItemStackRenderer.models.entrySet().iterator(); while (iter0.hasNext()) { TileEntityModelItemStackRenderer.TEModel model = iter0.next().getValue(); /* remove invisible models from the rendering cache*/ if (model.timer <= 0) { iter0.remove(); continue; } model.model.update(); model.timer--; } /* gun itemstack update */ Iterator<Map.Entry<ItemStack, TileEntityGunItemStackRenderer.GunEntry>> iter1 = TileEntityGunItemStackRenderer.models.entrySet().iterator(); while (iter1.hasNext()) { TileEntityGunItemStackRenderer.GunEntry model = iter1.next().getValue(); if (model.timer <= 0) { iter1.remove(); continue; } model.props.update(); model.timer--; } if (this.skinsTimer++ >= 30) { SkinHandler.checkSkinsFolder(); this.skinsTimer = 0; } RenderingHandler.updateEmitters(); GifTexture.updateTick(); } }
8,960
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
GunShootHandler.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/events/GunShootHandler.java
package mchorse.blockbuster.events; import java.lang.reflect.Field; 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.PacketGunInteract; import mchorse.blockbuster.network.common.guns.PacketGunReloading; import mchorse.blockbuster.utils.NBTUtils; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; 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.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * \* User: Evanechecssss * \* https://evanechecssss.github.io * \ */ public class GunShootHandler { private boolean canBeShotPress = true; private boolean canBeReloaded = true; private Field leftClickCounter = null; @SideOnly(Side.CLIENT) @SubscribeEvent(priority = EventPriority.HIGHEST) public void onTick(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.END) { return; } Minecraft mc = Minecraft.getMinecraft(); if (mc.player == null) { return; } ItemStack stack = mc.player.getHeldItemMainhand(); if (stack.getItem() instanceof ItemGun) { this.blockLeftClick(mc); this.handleShootKey(mc, stack); this.handleReloading(mc, stack); } } @SideOnly(Side.CLIENT) private void handleShootKey(Minecraft mc, ItemStack stack) { GunProps props = NBTUtils.getGunProps(stack); if (KeyboardHandler.gunShoot.isKeyDown()) { if (canBeShotPress && props.storedShotDelay == 0 && props.state == ItemGun.GunState.READY_TO_SHOOT) { Dispatcher.sendToServer(new PacketGunInteract(stack, mc.player.getEntityId())); canBeShotPress = false; return; } if (props.storedShotDelay == 0 && props.shootWhenHeld) { canBeShotPress = true; } } else { canBeShotPress = true; } } @SideOnly(Side.CLIENT) private void handleReloading(Minecraft mc, ItemStack stack) { GunProps props = NBTUtils.getGunProps(stack); if (KeyboardHandler.gunReload.isKeyDown() && canBeReloaded && props.state == ItemGun.GunState.READY_TO_SHOOT) { Dispatcher.sendToServer(new PacketGunReloading(stack, mc.player.getEntityId())); canBeReloaded = false; } else { canBeReloaded = true; } } @SideOnly(Side.CLIENT) private void blockLeftClick(Minecraft mc) { if (KeyboardHandler.gunShoot.conflicts(mc.gameSettings.keyBindAttack)) { if (leftClickCounter == null) { try { leftClickCounter = Minecraft.class.getDeclaredField("field_71429_W"); leftClickCounter.setAccessible(true); } catch (NoSuchFieldException | SecurityException e) { try { leftClickCounter = Minecraft.class.getDeclaredField("leftClickCounter"); leftClickCounter.setAccessible(true); } catch (NoSuchFieldException | SecurityException e1) {} } } try { this.leftClickCounter.setInt(mc, 10000); } catch (IllegalArgumentException | IllegalAccessException e) {} } } }
4,065
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ActionPanelRegisterEvent.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/events/ActionPanelRegisterEvent.java
package mchorse.blockbuster.events; import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel; import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions.GuiActionPanel; import mchorse.blockbuster.recording.actions.Action; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ActionPanelRegisterEvent extends Event { public GuiRecordingEditorPanel panel; public ActionPanelRegisterEvent(GuiRecordingEditorPanel panel) { this.panel = panel; } public void register(Class<? extends Action> action, GuiActionPanel<? extends Action> panel) { this.panel.panels.put(action, panel); } }
823
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
package-info.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/package-info.java
/** * <p> * This package used to be just a little bit refactored version of Mocap mod's * recording code, but since 1.4 update, this is no longer the same code it * used to be. * </p> * * <p> * Since I made enough changes to the source code, I think, I can count this * code fully as my own. In 1.4, I started from almost scratch: I removed * record and play threads and rewrote the recording and playback code from * scratch. That's what I remember, git history might disagree with me. * </p> * * <p> * However, I'm still going to honor EchebKeso and his Mocap mod, and going to * mention his name and/or his mod name, because he gave me a base start for * player recording. Thank you, EchebKeso :) * </p> * * @author mchorse * * @author EchebKeso * @link Minecraft Forum Post – http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/1445402-minecraft-motion-capture-mod-mocap-16-000 * @link Source Code – https://github.com/EchebKeso/Mocap */ package mchorse.blockbuster.recording;
1,030
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
RecordUtils.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/RecordUtils.java
package mchorse.blockbuster.recording; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.capabilities.recording.IRecording; import mchorse.blockbuster.capabilities.recording.Recording; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.recording.PacketApplyFrame; import mchorse.blockbuster.network.common.recording.PacketFramesLoad; import mchorse.blockbuster.network.common.recording.PacketRequestedFrames; import mchorse.blockbuster.network.common.recording.PacketUnloadFrames; import mchorse.blockbuster.recording.data.Frame; import mchorse.blockbuster.recording.data.Record; import mchorse.mclib.utils.ForgeUtils; import mchorse.mclib.utils.MathUtils; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.common.DimensionManager; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Utilities methods mostly to be used with recording code. Stuff like * broadcasting a message and sending records to players are located here. */ public class RecordUtils { /** * String version of {@link #broadcastMessage(ITextComponent)} */ public static void broadcastMessage(String message) { broadcastMessage(new TextComponentString(message)); } /** * I18n formatting version of {@link #broadcastMessage(ITextComponent)} */ public static void broadcastMessage(String string, Object... args) { broadcastMessage(new TextComponentTranslation(string, args)); } /** * Send given message to everyone on the server, to everyone. * * Invoke this method only on the server side. */ public static void broadcastMessage(ITextComponent message) { for (EntityPlayerMP player : ForgeUtils.getServerPlayers()) { player.sendMessage(message); } } /** * Send given error to everyone on the server, to everyone. * * Invoke this method only on the server side. */ public static void broadcastError(String string, Object... objects) { for (EntityPlayerMP player : ForgeUtils.getServerPlayers()) { Blockbuster.l10n.error(player, string, objects); } } /** * Send given error to everyone on the server, to everyone. * * Invoke this method only on the server side. */ public static void broadcastInfo(String string, Object... objects) { for (EntityPlayerMP player : ForgeUtils.getServerPlayers()) { Blockbuster.l10n.info(player, string, objects); } } /** * Checks whether player recording exists */ public static boolean isReplayExists(String filename) { return replayFile(filename).exists() || CommonProxy.manager.records.containsKey(filename); } /** * Get path to replay file (located in current world save's folder) */ public static File replayFile(String filename) { return Utils.serverFile("blockbuster/records", filename); } /** * This method gets a record that has been saved in the mod's jar file * @param filename * @return An {@link InputStream} object or null if no resource with this name is found */ public static InputStream getLocalReplay(String filename) { return RecordUtils.class.getResourceAsStream("/assets/blockbuster/records/" + filename + ".dat"); } /** * Get list of all available replays */ public static List<String> getReplays() { return Utils.serverFiles("blockbuster/records"); } /** * Get list of all available replays */ public static List<String> getReplayIterations(String replay) { List<String> list = new ArrayList<String>(); File replays = new File(DimensionManager.getCurrentSaveRootDirectory() + "/blockbuster/records"); File[] files = replays.listFiles(); if (files == null) { return list; } for (File file : files) { String name = file.getName(); if (file.isFile() && name.startsWith(replay) && name.contains(".dat~")) { list.add(name.substring(name.indexOf("~") + 1)); } } return list; } /** * Send record frames to given player from the server. * @param filename * @param player */ public static void sendRecordTo(String filename, EntityPlayerMP player) { sendRecordTo(filename, player, -1); } /** * Send record frames to given player from the server. * @param filename * @param player * @param callbackID the id of the callback that should be executed on the client. * -1 if no callback was created or should be executed. */ public static void sendRecordTo(String filename, EntityPlayerMP player, int callbackID) { if (!playerNeedsAction(filename, player)) { PacketFramesLoad packet = callbackID == -1 ? new PacketFramesLoad(filename, PacketFramesLoad.State.NOCHANGES) : new PacketFramesLoad(filename, PacketFramesLoad.State.NOCHANGES, callbackID); Dispatcher.sendTo(packet, player); return; } RecordManager manager = CommonProxy.manager; Record record = manager.records.get(filename); if (record == null) { try { record = new Record(filename); record.load(replayFile(filename)); manager.records.put(filename, record); } catch (FileNotFoundException e) { Blockbuster.l10n.error(player, "recording.not_found", filename); record = null; } catch (Exception e) { Blockbuster.l10n.error(player, "recording.read", filename); e.printStackTrace(); record = null; } } if (record != null) { record.resetUnload(); PacketFramesLoad packet = callbackID == -1 ? new PacketFramesLoad(filename, record.preDelay, record.postDelay, record.frames) : new PacketFramesLoad(filename, record.preDelay, record.postDelay, record.frames, callbackID); Dispatcher.sendTo(packet, player); System.out.println("Sent " + filename + " to " + player.getName()); } else { PacketFramesLoad packet = callbackID == -1 ? new PacketFramesLoad(filename, PacketFramesLoad.State.ERROR) : new PacketFramesLoad(filename, PacketFramesLoad.State.ERROR, callbackID); Dispatcher.sendTo(packet, player); } } /** * Send requested frames (for actor) to given player (from the server) */ public static void sendRequestedRecord(int id, String filename, EntityPlayerMP player) { Record record = CommonProxy.manager.records.get(filename); if (playerNeedsAction(filename, player) && record != null) { record.resetUnload(); Dispatcher.sendTo(new PacketRequestedFrames(id, record.filename, record.preDelay, record.postDelay, record.frames), player); System.out.println("Sent " + filename + " to " + player.getName() + " with " + id); } else if (record == null) { Blockbuster.l10n.error(player, "recording.not_found", filename); } } /** * Checks whether given player needs a new action, meaning, he has an older * version of given named action or he doesn't have this action at all. */ private static boolean playerNeedsAction(String filename, EntityPlayer player) { if (RecordUtils.getLocalReplay(filename) != null) { return false; } IRecording recording = Recording.get(player); if (recording.isFakePlayer()) { return false; } boolean has = recording.hasRecording(filename); long time = replayFile(filename).lastModified(); if (has && time > recording.recordingTimestamp(filename)) { recording.updateRecordingTimestamp(filename, time); return true; } if (!has) { recording.addRecording(filename, time); } return !has; } /** * Unload given record. It will send to all players a packet to unload a * record. */ public static void unloadRecord(Record record) { String filename = record.filename; for (EntityPlayerMP player : ForgeUtils.getServerPlayers()) { IRecording recording = Recording.get(player); if (recording.hasRecording(filename)) { recording.removeRecording(filename); Dispatcher.sendTo(new PacketUnloadFrames(filename), player); } } } /* records are saved on the server side */ public static void saveRecord(Record record) throws IOException { saveRecord(record, true); } public static void saveRecord(Record record, boolean unload) throws IOException { saveRecord(record, true, unload); } public static void saveRecord(Record record, boolean savePast, boolean unload) throws IOException { record.dirty = false; record.save(replayFile(record.filename), savePast); if (unload) { unloadRecord(record); } } public static void dirtyRecord(Record record) { record.dirty = true; unloadRecord(record); } /** * This method filters 360 degrees flips in the given frame list in the given rotation channel. * It does not modify the original list but returns a new list of frame copies. * @param frames the frames to filter * @param from from tick * @param to to tick (this tick will also be filtered) * @param channel the rotation channel of the frames to filter * @return the filtered frames. Returns an empty list if not enough frames are present to filter. */ public static List<Frame> discontinuityEulerFilter(List<Frame> frames, int from, int to, Frame.RotationChannel channel) { List<Frame> filteredFrames = new ArrayList<>(); if (to - from + 1 < 2) return filteredFrames; for (int i = from; i < frames.size() && i <= to; i++) { if (i == 0) { filteredFrames.add(frames.get(i)); continue; } Frame filteredFrame = frames.get(i).copy(); Frame prevFrame = frames.get(i - 1); if (i > from) { prevFrame = filteredFrames.get(i - from - 1); } switch (channel) { case BODY_YAW: float prev = (float) Math.toRadians(prevFrame.bodyYaw); float current = (float) Math.toRadians(frames.get(i).bodyYaw); filteredFrame.bodyYaw = (float) Math.toDegrees(MathUtils.filterFlips(prev, current)); break; case HEAD_PITCH: prev = (float) Math.toRadians(prevFrame.pitch); current = (float) Math.toRadians(frames.get(i).pitch); filteredFrame.pitch = (float) Math.toDegrees(MathUtils.filterFlips(prev, current)); break; case HEAD_YAW: /* filter both yawHead and yaw... I hope that is correct, Minecraft is weird */ prev = (float) Math.toRadians(prevFrame.yawHead); current = (float) Math.toRadians(frames.get(i).yawHead); filteredFrame.yawHead = (float) Math.toDegrees(MathUtils.filterFlips(prev, current)); prev = (float) Math.toRadians(prevFrame.yaw); current = (float) Math.toRadians(frames.get(i).yaw); filteredFrame.yaw = (float) Math.toDegrees(MathUtils.filterFlips(prev, current)); break; } filteredFrames.add(filteredFrame); } return filteredFrames; } /** * This method applies a frame at the given tick on the given entity * and synchronises with all players depending on which side this method has been executed on * @param entity the entity where the frame should be applied * @param record the recording with the frames * @param tick the tick to apply */ public static void applyFrameOnEntity(EntityLivingBase entity, Record record, int tick) { tick = MathUtils.clamp(tick, 0, record.frames.size() - 1); Frame frame = record.frames.get(tick); frame.apply(entity, true); /* Frame does not apply bodyYaw, EntityActor.updateDistance() does... TODO refactor this*/ entity.renderYawOffset = frame.bodyYaw; PacketApplyFrame packet = new PacketApplyFrame(frame, entity.getEntityId()); if (entity.world.isRemote) { /* send to server which will also sync it with all other players */ Dispatcher.sendToServer(packet); } else { /* already on server - sync with all players */ for (EntityPlayerMP player : ForgeUtils.getServerPlayers()) { Dispatcher.sendTo(packet, player); } } } }
14,082
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
RecordManager.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/RecordManager.java
package mchorse.blockbuster.recording; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.PacketCaption; import mchorse.blockbuster.network.common.recording.PacketPlayback; import mchorse.blockbuster.network.common.recording.PacketPlayerRecording; import mchorse.blockbuster.recording.actions.Action; import mchorse.blockbuster.recording.actions.DamageAction; import mchorse.blockbuster.recording.data.FrameChunk; import mchorse.blockbuster.recording.data.Mode; import mchorse.blockbuster.recording.data.Record; import mchorse.blockbuster.utils.EntityUtils; import mchorse.metamorph.api.MorphAPI; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Record manager * * This class responsible is responsible for managing record recorders and * players for entity players and actors. */ public class RecordManager { /** * Loaded records */ public Map<String, Record> records = new HashMap<String, Record>(); /** * Incomplete chunk frame only records (for recording big records) */ public Map<String, FrameChunk> chunks = new HashMap<String, FrameChunk>(); /** * Currently running record recorders (I have something to do about the * name) */ public Map<EntityPlayer, RecordRecorder> recorders = new HashMap<EntityPlayer, RecordRecorder>(); /** * Me: No, not {@link EntityPlayer}s, say record pla-yers, pla-yers... * Also me in 2020: What a cringe... */ public Map<EntityLivingBase, RecordPlayer> players = new HashMap<EntityLivingBase, RecordPlayer>(); /** * Scheduled recordings */ public Map<EntityPlayer, ScheduledRecording> scheduled = new HashMap<EntityPlayer, ScheduledRecording>(); /** * Get action list for given player */ public List<Action> getActions(EntityPlayer player) { RecordRecorder recorder = this.recorders.get(player); return recorder == null ? null : recorder.actions; } public boolean record(String filename, EntityPlayer player, Mode mode, boolean teleportBack, boolean notify, Runnable runnable) { return this.record(filename, player, mode, teleportBack, notify, 0, runnable); } /** * Start recording given player to record with given filename */ public boolean record(String filename, EntityPlayer player, Mode mode, boolean teleportBack, boolean notify, int offset, Runnable runnable) { Runnable proxy = () -> { if (offset > 0 && this.records.get(filename) != null && notify) { RecordPlayer recordPlayer = this.play(filename, player, Mode.ACTIONS, false); recordPlayer.tick = offset; EntityUtils.setRecordPlayer(player, recordPlayer.realPlayer()); } if (runnable != null) { runnable.run(); } }; if (this.recorders.containsKey(player)) { proxy.run(); } if (filename.isEmpty() || this.halt(player, false, notify)) { if (filename.isEmpty()) { RecordUtils.broadcastError("recording.empty_filename"); } return false; } for (RecordRecorder recorder : this.recorders.values()) { if (recorder.record.filename.equals(filename)) { RecordUtils.broadcastInfo("recording.recording", filename); return false; } } RecordRecorder recorder = new RecordRecorder(new Record(filename), mode, player, teleportBack); recorder.offset = offset; if (player.world.isRemote) { this.recorders.put(player, recorder); } else { this.setupPlayerData(recorder, player); CommonProxy.damage.addDamageControl(recorder, player); this.scheduled.put(player, new ScheduledRecording(recorder, player, proxy, (int) (Blockbuster.recordingCountdown.get() * 20), offset)); } return true; } private void setupPlayerData(RecordRecorder recorder, EntityPlayer player) { NBTTagCompound tag = new NBTTagCompound(); player.writeEntityToNBT(tag); recorder.record.playerData = tag; if (MPMHelper.isLoaded()) { tag = MPMHelper.getMPMData(player); if (tag != null) { recorder.record.playerData.setTag("MPMData", tag); } } } /** * Stop recording given player */ public boolean halt(EntityPlayer player, boolean hasDied, boolean notify) { return this.halt(player, hasDied, notify, false); } /** * Stop recording given player */ public boolean halt(EntityPlayer player, boolean hasDied, boolean notify, boolean canceled) { /* Stop countdown */ ScheduledRecording scheduled = this.scheduled.get(player); if (scheduled != null) { this.scheduled.remove(player); Dispatcher.sendTo(new PacketCaption(), (EntityPlayerMP) player); return true; } /* Stop the recording via command or whatever the source is */ RecordRecorder recorder = this.recorders.get(player); if (recorder != null) { Record record = recorder.record; String filename = record.filename; if (!canceled && hasDied && !record.actions.isEmpty()) { record.addAction(record.actions.size() - 1, new DamageAction(200.0F)); } else { recorder.stop(player); } /* Remove action preview for previously recorded actions */ RecordPlayer recordPlayer = this.players.get(player); if (recordPlayer != null && recordPlayer.realPlayer) { this.players.remove(player); EntityUtils.setRecordPlayer(player, null); } if (!canceled) { /* Apply old player recording */ try { Record oldRecord = this.get(filename); recorder.applyOld(oldRecord); } catch (Exception e) {} this.records.put(filename, record); } this.recorders.remove(player); MorphAPI.demorph(player); if (notify) { CommonProxy.damage.restoreDamageControl(recorder, player.world); Dispatcher.sendTo(new PacketPlayerRecording(false, "", 0, canceled), (EntityPlayerMP) player); } return true; } return false; } /** * Version with default tick parameter */ public RecordPlayer play(String filename, EntityLivingBase actor, Mode mode, boolean kill) { return this.play(filename, actor, mode, 0, kill); } /** * Start playback from given filename and given actor. You also have to * specify the mode of playback. */ public RecordPlayer play(String filename, EntityLivingBase actor, Mode mode, int tick, boolean kill) { if (this.players.containsKey(actor)) { return null; } try { Record record = this.get(filename); if (record.frames.size() == 0) { RecordUtils.broadcastError("recording.empty_record", filename); return null; } RecordPlayer playback = new RecordPlayer(record, mode, actor); playback.tick = tick; playback.kill = kill; playback.applyFrame(tick, actor, true); EntityUtils.setRecordPlayer(actor, playback); this.players.put(actor, playback); return playback; } catch (FileNotFoundException e) { RecordUtils.broadcastError("recording.not_recorded", filename); } catch (Exception e) { RecordUtils.broadcastError("recording.read", filename); e.printStackTrace(); } return null; } /** * Stop playback for the given record player */ public void stop(RecordPlayer actor) { if (!this.players.containsKey(actor.actor)) { return; } if (actor.actor.getHealth() > 0.0F) { if (actor.kill) { actor.actor.dismountRidingEntity(); if (actor.realPlayer) { if (actor.actor instanceof EntityPlayerMP) { Dispatcher.sendTo(new PacketPlayback(actor.actor.getEntityId(), false, actor.realPlayer, ""), (EntityPlayerMP) actor.actor); } } else { actor.actor.setDead(); if (actor.actor instanceof EntityPlayer) { actor.actor.world.getMinecraftServer().getPlayerList().playerLoggedOut((EntityPlayerMP) actor.actor); } } } else { Dispatcher.sendToTracked(actor.actor, new PacketPlayback(actor.actor.getEntityId(), false, actor.realPlayer, "")); } } this.players.remove(actor.actor); EntityUtils.setRecordPlayer(actor.actor, null); } public boolean cancel(EntityPlayer player) { return this.halt(player, false, true, true); } /** * Reset the tracking manager data */ public void reset() { for (Record record : this.records.values()) { if (record.dirty) { try { record.save(RecordUtils.replayFile(record.filename)); } catch (Exception e) { e.printStackTrace(); } } } this.records.clear(); this.chunks.clear(); this.recorders.clear(); this.players.clear(); } /** * Abort the recording of action for given player */ public void abort(EntityPlayer player) { if (this.recorders.containsKey(player)) { RecordRecorder recorder = this.recorders.remove(player); RecordUtils.broadcastError("recording.logout", recorder.record.filename); } } /** * Get record by the filename * * If a record by the filename doesn't exist, then record manager tries to * load this record. */ public Record get(String filename) throws Exception { Record record = this.records.get(filename); if (record == null) { File file = RecordUtils.replayFile(filename); record = new Record(filename); record.load(file); this.records.put(filename, record); } return record; } /** * Get record on the client side */ @SideOnly(Side.CLIENT) public Record getClient(String filename) { Record record = this.records.get(filename); if (record == null) { try { InputStream stream = RecordUtils.getLocalReplay(filename); NBTTagCompound tag = CompressedStreamTools.readCompressed(stream); record = new Record(filename); record.load(tag); this.records.put(filename, record); } catch (Exception e) {} } return record; } /** * Unload old records and check scheduled actions */ public void tick() { if (Blockbuster.recordUnload.get() && !this.records.isEmpty()) { this.checkAndUnloadRecords(); } if (!this.scheduled.isEmpty()) { this.checkScheduled(); } } /** * Check for any unloaded record and unload it if needed requirements are * met. */ private void checkAndUnloadRecords() { Iterator<Map.Entry<String, Record>> iterator = this.records.entrySet().iterator(); while (iterator.hasNext()) { Record record = iterator.next().getValue(); record.unload--; if (record.unload <= 0) { iterator.remove(); RecordUtils.unloadRecord(record); try { if (record.dirty) { record.save(RecordUtils.replayFile(record.filename)); record.dirty = false; } } catch (IOException e) { e.printStackTrace(); } } } } /** * Check for scheduled records and countdown them. */ private void checkScheduled() { Iterator<ScheduledRecording> it = this.scheduled.values().iterator(); while (it.hasNext()) { ScheduledRecording record = it.next(); if (record.countdown % 2 == 0) { IMessage message = new PacketCaption(new TextComponentTranslation("blockbuster.start_recording", record.recorder.record.filename, record.countdown / 20F)); Dispatcher.sendTo(message, (EntityPlayerMP) record.player); } if (record.countdown <= 0) { record.run(); this.recorders.put(record.player, record.recorder); Dispatcher.sendTo(new PacketPlayerRecording(true, record.recorder.record.filename, record.offset, false), (EntityPlayerMP) record.player); it.remove(); continue; } record.countdown--; } } public void rename(String old, Record record) { RecordUtils.unloadRecord(record); this.records.remove(old); this.records.put(record.filename, record); for (String iter : RecordUtils.getReplayIterations(old)) { File oldIter = new File(RecordUtils.replayFile(old).getAbsolutePath() + "~" + iter); oldIter.renameTo(new File(RecordUtils.replayFile(record.filename).getAbsolutePath() + "~" + iter)); } RecordUtils.replayFile(old).delete(); } }
15,405
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
RecordRecorder.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/RecordRecorder.java
package mchorse.blockbuster.recording; import java.util.ArrayList; import java.util.List; import mchorse.blockbuster.recording.actions.Action; import mchorse.blockbuster.recording.capturing.PlayerTracker; import mchorse.blockbuster.recording.data.Frame; import mchorse.blockbuster.recording.data.Mode; import mchorse.blockbuster.recording.data.Record; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.math.MathHelper; /** * Record recorder class * * This thing is responsible for recording a record. It can record actions and * frames to the given recorder. * * Yeah, kinda funky naming, but it is the <s>not</s> best naming, eva! */ public class RecordRecorder { /** * Initial record */ public Record record; /** * List of actions which will be saved every time {@link #record(EntityPlayer)} * method is invoked. */ public List<Action> actions = new ArrayList<Action>(); /** * Recording mode (record actions, frames or both) */ public Mode mode; /** * Current recording tick */ public int tick = 0; /** * Recording offset */ public int offset = 0; /** * Whether recorded player should be teleported back */ public boolean teleportBack; /** * First frame (to restore the position) */ private Frame first; /** * The offset of yaw between before and after {{@link net.minecraft.util.math.MathHelper.wrapDegrees(double)} */ private float yawOffset; /** * Player tracker, this dude is responsible for tracking inventory slots, * swing progress and elytra flying updates */ public PlayerTracker tracker; public RecordRecorder(Record record, Mode mode, EntityPlayer player, boolean teleportBack) { this.record = record; this.mode = mode; this.teleportBack = teleportBack; this.first = new Frame(); this.first.fromPlayer(player); this.yawOffset = this.first.yaw - MathHelper.wrapDegrees(this.first.yaw); if (mode == Mode.ACTIONS || mode == Mode.BOTH) { this.tracker = new PlayerTracker(this); } } /** * Record frame from the player */ public void record(EntityPlayer player) { boolean both = this.mode == Mode.BOTH; if (this.mode == Mode.FRAMES || both) { Frame frame = new Frame(); frame.fromPlayer(player); frame.yaw -= this.yawOffset; frame.yawHead -= this.yawOffset; frame.bodyYaw -= this.yawOffset; frame.mountYaw -= this.yawOffset; this.record.frames.add(frame); } if (this.mode == Mode.ACTIONS || both) { this.tracker.track(player); List<Action> list = null; if (!this.actions.isEmpty()) { list = new ArrayList<Action>(); list.addAll(this.actions); this.actions.clear(); } this.record.actions.add(list); } this.tick++; } public void stop(EntityPlayer player) { if (this.teleportBack && player instanceof EntityPlayerMP) { ((EntityPlayerMP) player).connection.setPlayerLocation(this.first.x, this.first.y, this.first.z, this.first.yaw, this.first.pitch); } } public void applyOld(Record oldRecord) { this.record.frames.addAll(oldRecord.frames); if (this.offset > 0) { List<List<Action>> actions = this.record.actions; int newSize = this.offset + actions.size(); this.record.actions = oldRecord.actions; if (this.record.actions.size() < newSize) { while (this.record.actions.size() < newSize) { this.record.actions.add(null); } } for (int i = 0; i < actions.size(); i++) { this.record.addActions(this.offset + i, actions.get(i)); } } } }
4,195
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
ScheduledRecording.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/ScheduledRecording.java
package mchorse.blockbuster.recording; import net.minecraft.entity.player.EntityPlayer; /** * Scheduled recorder class */ public class ScheduledRecording { public RecordRecorder recorder; public EntityPlayer player; public Runnable runnable; public int countdown; public int offset; public ScheduledRecording(RecordRecorder recorder, EntityPlayer player, Runnable runnable, int countdown, int offset) { this.recorder = recorder; this.player = player; this.runnable = runnable; this.countdown = countdown; this.offset = offset; } public void run() { if (this.runnable != null) { this.runnable.run(); } } }
731
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
MPMHelper.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/MPMHelper.java
package mchorse.blockbuster.recording; import java.lang.reflect.Method; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.Loader; /** * MPM helper class * * This class is responsible for setting and getting current MPM model data for * given player. Reden (Charles) helped me to figure out this stuff. */ public class MPMHelper { /* Reflection fields */ public static Method get; public static Method set; public static Method getThing; /** * Checks whether MPM mod is loaded */ public static boolean isLoaded() { return Loader.isModLoaded("moreplayermodels"); } /** * Initiate method fields for later usage with get and set MPM data methods */ public static void init() { try { Class clazz = Class.forName("noppes.mpm.ModelData"); get = clazz.getMethod("writeToNBT"); set = clazz.getMethod("readFromNBT", NBTTagCompound.class); getThing = clazz.getMethod("get", EntityPlayer.class); } catch (Exception e) { e.printStackTrace(); } } /** * Gets MPM data from given player */ public static NBTTagCompound getMPMData(EntityPlayer entity) { if (get == null) { init(); } if (get != null) { try { return (NBTTagCompound) get.invoke(getThing.invoke(null, entity)); } catch (Exception e) { e.printStackTrace(); } } return null; } /** * Sets MPM data on a given player */ public static void setMPMData(EntityPlayer entity, NBTTagCompound tag) { if (set == null) { init(); } if (set != null) { try { set.invoke(getThing.invoke(null, entity), tag); } catch (Exception e) { e.printStackTrace(); } } } }
2,157
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
LTHelper.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/LTHelper.java
package mchorse.blockbuster.recording; import mchorse.blockbuster.recording.data.Frame; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.Vec3d; import java.lang.reflect.Method; /** * LittleTiles helper method * * This bad boy is responsible contacting LittleTile API (introduced in v1.5.0-pre199_31_mc1.12.2) * to allow opening the doors. Big thanks to CreativeMD for helping out with this issue! * * @link https://www.curseforge.com/minecraft/mc-mods/littletiles/files/2960578 */ public class LTHelper { private static Method method; private static boolean weTried; public static boolean playerRightClickServer(EntityPlayer player, Frame frame) { try { if (method == null && !weTried) { weTried = true; Class clazz = Class.forName("com.creativemd.littletiles.common.api.LittleTileAPI"); method = clazz.getMethod("playerRightClickServer", EntityPlayer.class, Vec3d.class, Vec3d.class); } } catch (Exception e) {} if (method != null) { try { player.rotationPitch = frame.pitch; player.rotationYaw = frame.yaw; Vec3d pos = new Vec3d(frame.x, frame.y, frame.z); Vec3d look = player.getLookVec().scale(8); pos = pos.addVector(0, player.getEyeHeight(), 0); Object object = method.invoke(null, player, pos, pos.add(look)); return object instanceof Boolean && ((Boolean) object).booleanValue(); } catch (Exception e) { e.printStackTrace(); } } return false; } }
1,780
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Utils.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/Utils.java
package mchorse.blockbuster.recording; import net.minecraftforge.common.DimensionManager; import java.io.File; import java.util.ArrayList; import java.util.List; public class Utils { /** * Get path to server file in given folder */ public static File serverFile(String folder, String filename) { File file = new File(DimensionManager.getCurrentSaveRootDirectory() + "/" + folder); if (!file.exists()) { file.mkdirs(); } return new File(file, filename + ".dat"); } /** * Get list of all available replays */ public static List<String> serverFiles(String folder) { List<String> list = new ArrayList<String>(); File replays = new File(DimensionManager.getCurrentSaveRootDirectory() + "/" + folder); File[] files = replays.listFiles(); if (files == null) { return list; } for (File file : files) { String name = file.getName(); if (file.isFile() && name.endsWith(".dat")) { int index = name.lastIndexOf("."); list.add(name.substring(0, index)); } } return list; } }
1,248
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
RecordPlayer.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/RecordPlayer.java
package mchorse.blockbuster.recording; import java.util.Queue; import com.google.common.collect.Queues; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.blockbuster.recording.scene.Replay; import mchorse.blockbuster.network.Dispatcher; import mchorse.blockbuster.network.common.PacketActorPause; import mchorse.blockbuster.network.common.recording.PacketPlayback; import mchorse.blockbuster.network.common.recording.PacketSyncTick; import mchorse.blockbuster.recording.data.Frame; import mchorse.blockbuster.recording.data.Mode; import mchorse.blockbuster.recording.data.Record; import mchorse.blockbuster.utils.EntityUtils; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityTracker; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.SPacketEntityTeleport; import net.minecraft.util.math.MathHelper; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; /** * Record player class * * This thing is responsible for playing given record. It applies frames and * actions from the record instance on the given actor. */ public class RecordPlayer { /** * Record from which this player is going to play */ public Record record; /** * Play mode */ public Mode mode; /** * Entity which is used by this record player to replay the action */ public EntityLivingBase actor; /** * Current tick */ public int tick = 0; /** * Whether to kill an actor when player finished playing */ public boolean kill = false; /** * Is this player is playing */ public boolean playing = true; /** * Sync mode - pauses the playback once hit the end */ public boolean sync = false; /** * It might be null */ private Replay replay; public boolean realPlayer; public Queue<IMessage> unsentPackets = Queues.<IMessage>newArrayDeque(); public boolean actorUpdated; public RecordPlayer(Record record, Mode mode, EntityLivingBase actor) { this.record = record; this.mode = mode; this.actor = actor; } public Replay getReplay() { return replay; } public void setReplay(Replay replay) { this.replay = replay; if (this.record != null) { this.record.setReplay(this.replay); } } public RecordPlayer realPlayer() { this.realPlayer = true; return this; } /** * Check if the record player is finished */ public boolean isFinished() { boolean isFinished = this.record != null && this.tick - this.record.preDelay - this.record.postDelay >= this.record.getLength(); if (isFinished && this.sync && this.playing) { this.pause(); return false; } return isFinished; } /** * Get appropriate amount of real ticks (for accessing current * action or something like this) */ public int getTick() { return Math.max(0, this.record == null ? this.tick : this.tick - this.record.preDelay); } /** * Get current frame */ public Frame getCurrentFrame() { return this.record.getFrame(this.getTick()); } /** * It should be called before world tick */ public void playActions() { if (!this.playing || this.isFinished()) { return; } if (this.record != null) { if (this.mode == Mode.ACTIONS || this.mode == Mode.BOTH) this.applyAction(this.tick, actor, false); this.record.resetUnload(); } } public void next() { this.next(this.actor); } /** * Apply current frame and advance to the next one */ public void next(EntityLivingBase actor) { if (this.record != null) { this.record.resetUnload(); } if (!this.playing || this.isFinished()) { return; } if (this.record != null) { if (this.mode == Mode.FRAMES || this.mode == Mode.BOTH) this.applyFrame(this.tick, actor, false); this.record.resetUnload(); } /* Align the body with the head on spawn */ if (this.tick == 0) { actor.renderYawOffset = actor.rotationYaw; } this.tick++; this.actorUpdated = true; } /** * Pause the playing actor */ public void pause() { this.playing = false; this.actor.noClip = true; this.actor.setEntityInvulnerable(true); this.applyFrame(this.tick - 1, this.actor, true); if (this.actor.isServerWorld()) { this.record.applyPreviousMorph(this.actor, this.replay, this.tick, Record.MorphType.PAUSE); this.sendToTracked(new PacketActorPause(this.actor.getEntityId(), true, this.tick)); } } /** * Resume the paused actor */ public void resume(int tick) { if (tick >= 0) { this.tick = tick; } this.playing = true; this.actor.noClip = false; if (!this.actor.world.isRemote && this.replay != null) { this.actor.setEntityInvulnerable(this.replay.invincible); } this.applyFrame(this.tick, this.actor, true); if (this.actor.isServerWorld()) { this.record.applyPreviousMorph(this.actor, this.replay, tick, Record.MorphType.FORCE); this.sendToTracked(new PacketActorPause(this.actor.getEntityId(), false, this.tick)); } } /** * Make an actor go to the given tick */ public void goTo(int tick, boolean actions) { int preDelay = this.record.preDelay; int original = tick; if (tick > this.record.frames.size() + this.record.preDelay) { tick = this.record.frames.size() + this.record.preDelay - 1; } tick -= preDelay; int min = Math.min(this.tick - this.record.preDelay, tick); int max = Math.max(this.tick - this.record.preDelay, tick); if (actions) { for (int i = min; i < max; i++) { this.record.applyAction(i, this.actor); } } this.tick = original; this.record.resetUnload(); this.record.applyFrame(this.playing ? tick : Math.max(0, tick - 1), this.actor, true, this.realPlayer); if (actions) { this.record.applyAction(tick, this.actor); if (this.replay != null) { this.record.applyPreviousMorph(this.actor, this.replay, tick, this.playing ? Record.MorphType.FORCE : Record.MorphType.PAUSE); } } if (this.actor.isServerWorld()) { this.sendToTracked(new PacketActorPause(this.actor.getEntityId(), !this.playing, this.tick)); } } /** * Start the playback, but with default tick argument */ public void startPlaying(String filename, boolean kill) { this.startPlaying(filename, 0, kill); } /** * Start the playback, invoked by director block (more specifically by * DirectorTileEntity). */ public void startPlaying(String filename, int tick, boolean kill) { this.tick = tick; this.kill = kill; this.sync = false; //TODO this should rather be in Replay.apply(EntityPlayer) // but there seems to be no way to then revert invulnerability based on Replay instance when recording stops if (!this.actor.world.isRemote && this.replay != null) { this.actor.setEntityInvulnerable(this.replay.invincible); } this.applyFrame(this.playing ? tick : tick - 1, this.actor, true); EntityUtils.setRecordPlayer(this.actor, this); this.sendToTracked(new PacketPlayback(this.actor.getEntityId(), true, this.realPlayer, filename, this.replay)); if (this.realPlayer && this.actor instanceof EntityPlayerMP) { Dispatcher.sendTo(new PacketPlayback(this.actor.getEntityId(), true, this.realPlayer, filename, this.replay), (EntityPlayerMP) this.actor); } } /** * Stop playing */ public void stopPlaying() { CommonProxy.manager.stop(this); this.actor.noClip = false; if (!this.actor.world.isRemote && this.replay != null && this.replay.invincible == true) { this.actor.setEntityInvulnerable(false); } } public void applyFrame(int tick, EntityLivingBase target, boolean force) { tick -= this.record.preDelay; if (tick < 0) { tick = 0; } else if (tick >= this.record.frames.size()) { tick = this.record.frames.size() - 1; } this.record.applyFrame(tick, target, force, this.realPlayer); } public void applyAction(int tick, EntityLivingBase target, boolean safe) { this.record.applyAction(tick - this.record.preDelay, target, safe); } public void sendToTracked(IMessage packet) { if (this.actor.world.getEntityByID(this.actor.getEntityId()) != this.actor) { this.unsentPackets.add(packet); } else { Dispatcher.sendToTracked(this.actor, packet); } } public void checkAndSpawn() { /* Checks whether actor isn't already spawned in the world */ if (this.actor.world.getEntityByID(this.actor.getEntityId()) != this.actor) { if (this.actor instanceof EntityActor) { if (!this.actor.isDead) { this.actor.world.spawnEntity(this.actor); EntityPlayer player = ((EntityActor) this.actor).fakePlayer; player.posX = this.actor.posX; player.posY = this.actor.posY; player.posZ = this.actor.posZ; this.actor.world.loadedEntityList.add(((EntityActor) this.actor).fakePlayer); } } else if (this.actor instanceof EntityPlayer) { if (this.record.playerData != null) { if (!this.realPlayer) { this.actor.readEntityFromNBT(this.record.playerData); } if (MPMHelper.isLoaded() && this.record.playerData.hasKey("MPMData", NBT.TAG_COMPOUND)) { MPMHelper.setMPMData((EntityPlayer) this.actor, this.record.playerData.getCompoundTag("MPMData")); } } if (!this.realPlayer && !this.actor.isDead) { this.actor.world.getMinecraftServer().getPlayerList().playerLoggedIn((EntityPlayerMP) this.actor); } } while (!this.unsentPackets.isEmpty()) { Dispatcher.sendToTracked(this.actor, this.unsentPackets.poll()); } } } }
11,510
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
FrameChunk.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/data/FrameChunk.java
package mchorse.blockbuster.recording.data; import java.util.ArrayList; import java.util.List; /** * Frame chunk class * * This class is responsible for storing unfinished loading frames with * records from the client. */ public class FrameChunk { /** * List of frame lists. The list to store them all... */ public List<List<Frame>> frames; /** * How much chunks this chunk should store. */ public int count; /** * Recording offset */ public int offset; public FrameChunk(int count, int offset) { this.frames = new ArrayList<List<Frame>>(count); this.count = count; this.offset = offset; for (int i = 0; i < count; i++) { this.frames.add(null); } } /** * Does this chunked storage is fully filled */ public boolean isFilled() { for (int i = 0; i < this.count; i++) { if (this.frames.get(i) == null) { return false; } } return true; } /** * Add chunked frames to the frames storage */ public void add(int index, List<Frame> frames) { this.frames.set(index, frames); } /** * Compile all frames into one list */ public List<Frame> compile(List<Frame> oldFrames) { List<Frame> output = new ArrayList<Frame>(); if (this.offset > 0) { List<Frame> merged = new ArrayList<Frame>(); for (List<Frame> frames : this.frames) { merged.addAll(frames); } int newSize = this.offset + merged.size(); for (int i = 0, c = Math.max(newSize, oldFrames.size()); i < c; i++) { Frame frame; if (i < this.offset) { frame = i < oldFrames.size() ? oldFrames.get(i) : merged.get(0).copy(); } else if (i > newSize) { frame = oldFrames.get(i); } else { int index = i - this.offset; frame = index < merged.size() ? merged.get(index) : oldFrames.get(i); } output.add(frame); } } else { for (List<Frame> frames : this.frames) { output.addAll(frames); } } return output; } }
2,544
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Mode.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/data/Mode.java
package mchorse.blockbuster.recording.data; /** * Mode enumeration. This enumeration represents how to playback the * record. Not really sure if BOTH is going to be used at all, but ACTIONS * and FRAMES definitely would. */ public enum Mode { ACTIONS, FRAMES, BOTH; }
276
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Record.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/data/Record.java
package mchorse.blockbuster.recording.data; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.aperture.CameraHandler; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.blockbuster.recording.actions.Action; import mchorse.blockbuster.recording.actions.ActionRegistry; import mchorse.blockbuster.recording.actions.MorphAction; import mchorse.blockbuster.recording.actions.MountingAction; import mchorse.blockbuster.recording.scene.Replay; import mchorse.mclib.utils.MathUtils; import mchorse.metamorph.api.morphs.AbstractMorph; import mchorse.metamorph.api.morphs.utils.ISyncableMorph; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.MovementInput; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.io.FilenameUtils; import javax.annotation.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * This class stores actions and frames states for a recording (to be played * back or while recording). * * There's two list arrays in this class, index in both of these arrays * represents the frame position (0 is first frame). Frames list is always * populated, but actions list will contain some nulls. */ public class Record { public static final FoundAction ACTION = new FoundAction(); public static final MorphAction MORPH = new MorphAction(); /** * Signature of the recording. If the first short of the record file isn't * this file, then the */ public static final short SIGNATURE = 148; /** * Filename of this record */ public String filename; /** * Version of this record */ public short version = SIGNATURE; /** * Pre-delay same thing as post-delay but less useful */ public int preDelay = 0; /** * Post-delay allows actors to stay longer on the screen before * whoosing into void */ public int postDelay = 0; /** * Recorded actions. * The list contains every frame of the recording. * If no action is present at a frame, the frame will be null. */ public List<List<Action>> actions = new ArrayList<List<Action>>(); /** * Recorded frames */ public List<Frame> frames = new ArrayList<Frame>(); /** * Player data which was recorded when player started recording */ public NBTTagCompound playerData; /** * Unload timer. Used only on server side. */ public int unload; /** * Whether this record has changed elements */ public boolean dirty; /** * Can be null */ private Replay replay; public Record(String filename) { this.filename = filename; this.resetUnload(); } /** * Set this replay to the reference of the provided replay * @param replay */ public void setReplay(Replay replay) { this.replay = replay; } public Replay getReplay() { return this.replay; } /** * Get the full length (including post and pre delays) of this record in frames/ticks */ public int getFullLength() { return this.preDelay + this.getLength() + this.postDelay; } /** * Get the length of this record in frames/ticks */ public int getLength() { return Math.max(this.actions.size(), this.frames.size()); } /** * @return actions at the given tick. Can return null if nothing is present there. */ public List<Action> getActions(int tick) { if (tick >= this.actions.size() || tick < 0) { return null; } return this.actions.get(tick); } /** * @param tick negative values are allowed as they will return null * @param index negative values are allowed as they will return null * @return action at the given tick and index. * Returns null if none was found or if the tick or index are out of bounds. */ public Action getAction(int tick, int index) { List<Action> actions = this.getActions(tick); if (actions != null && index >= 0 && index < actions.size()) { return actions.get(index); } return null; } /** * If fromIndex0 and toIndex0 are both -1 every action at the frame in the range will be added. * @param fromTick0 from tick, inclusive * @param toTick0 to tick, inclusive * @param fromIndex0 from action index, inclusive. Can be -1 only together with toIndex0. * @param toIndex0 to action index, inclusive. Can be -1 only together with fromIndex0. * @return a new list containing the actions in the specified ranges. The list can contain null values. * @throws IndexOutOfBoundsException if fromTick < 0 || toTick > size of {@link #actions} */ public List<List<Action>> getActions(int fromTick0, int toTick0, int fromIndex0, int toIndex0) { int fromIndex = Math.min(fromIndex0, toIndex0); int toIndex = Math.max(fromIndex0, toIndex0); int fromTick = Math.min(fromTick0, toTick0); int toTick = Math.max(fromTick0, toTick0); if (fromTick0 < 0 || toTick0 < 0 || ((fromIndex0 != -1 || toIndex0 != -1) && fromIndex0 < 0 && toIndex0 < 0) || toTick >= this.actions.size()) { return new ArrayList<>(); } List<List<Action>> actionRange = this.actions.subList(fromTick, toTick + 1); if (actionRange != null) { actionRange = new ArrayList<>(actionRange); for (int i = 0; i < actionRange.size(); i++) { List<Action> frame = actionRange.get(i); if (frame != null && !frame.isEmpty()) { if (fromIndex == -1 && toIndex == -1) { actionRange.set(i, new ArrayList<>(frame)); } else if (fromIndex >= frame.size()) { actionRange.set(i, null); } else { int i0 = MathUtils.clamp(fromIndex, 0, frame.size() - 1); int i1 = MathUtils.clamp(toIndex + 1, 0, frame.size()); actionRange.set(i, new ArrayList<>(frame.subList(i0, i1))); } } else { actionRange.set(i, null); } } } return actionRange; } /** * @param fromTick0 from tick, inclusive * @param toTick0 to tick, inclusive * @return a new list containing the actions in the specified ranges. The list can contain null values. * @throws IndexOutOfBoundsException if fromTick < 0 || toTick > size of {@link #actions} */ public List<List<Action>> getActions(int fromTick0, int toTick0) { return this.getActions(fromTick0, toTick0, -1, -1); } /** * @return convert the given action list into a boolean mask, which can be used for deletion. * Returns an empty list if the specified tick is out of range. */ public List<List<Boolean>> getActionsMask(int fromTick, List<List<Action>> actions) { if (fromTick < 0 || fromTick >= this.actions.size()) { return new ArrayList<>(); } List<List<Boolean>> mask = new ArrayList<>(); for (int t = fromTick; t < this.actions.size() && t - fromTick < actions.size(); t++) { List<Boolean> maskFrame = new ArrayList<>(); if (actions.get(t - fromTick) != null && this.actions.get(t) != null && !this.actions.get(t).isEmpty()) { for (int a = 0; a < this.actions.get(t).size(); a++) { maskFrame.add(actions.get(t - fromTick).contains(this.actions.get(t).get(a))); } } else { maskFrame.add(false); } mask.add(maskFrame); } return mask; } /** * @param tick * @param action * @return the index of the provided action at the provided tick. * If nothing is found or if the tick is out of range or if the tick has no actions -1 will be returned. */ public int getActionIndex(int tick, Action action) { if (tick < 0 || tick >= this.actions.size() || this.actions.get(tick) == null || this.actions.get(tick).isEmpty() || action == null) { return -1; } for (int a = 0; a < this.actions.get(tick).size(); a++) { if (this.actions.get(tick).get(a) == action) { return a; } } return -1; } /** * @param action * @return int array {tick, index} of the found action. If nothing was found the values will be -1 */ public int[] findAction(Action action) { if (action == null) { return new int[]{-1, -1}; } for (int t = 0; t < this.actions.size(); t++) { int i = this.getActionIndex(t, action); if (i != -1) return new int[]{t, i}; } return new int[]{-1, -1}; } /** * Get frame on given tick */ public Frame getFrame(int tick) { if (tick >= this.frames.size() || tick < 0) { return null; } return this.frames.get(tick); } /** * Reset unloading timer */ public void resetUnload() { this.unload = Blockbuster.recordUnloadTime.get(); } public void applyFrame(int tick, EntityLivingBase actor, boolean force) { this.applyFrame(tick, actor, force, false); } /** * Apply a frame at given tick on the given actor. */ public void applyFrame(int tick, EntityLivingBase actor, boolean force, boolean realPlayer) { if (tick >= this.frames.size() || tick < 0) { return; } Frame frame = this.frames.get(tick); frame.apply(actor, this.replay, force); if (realPlayer) { actor.setLocationAndAngles(frame.x, frame.y, frame.z, frame.yaw, frame.pitch); actor.motionX = frame.motionX; actor.motionY = frame.motionY; actor.motionZ = frame.motionZ; actor.onGround = frame.onGround; if (frame.hasBodyYaw) { actor.renderYawOffset = frame.bodyYaw; } if (actor.world.isRemote) { this.applyClientMovement(actor, frame); } actor.setSneaking(frame.isSneaking); actor.setSprinting(frame.isSprinting); if (actor.world.isRemote) { this.applyFrameClient(actor, null, frame); } } if (actor.world.isRemote && Blockbuster.actorFixY.get()) { actor.posY = frame.y; } Frame prev = this.frames.get(Math.max(0, tick - 1)); if (realPlayer || !actor.world.isRemote) { actor.lastTickPosX = prev.x; actor.lastTickPosY = prev.y; actor.lastTickPosZ = prev.z; actor.prevPosX = prev.x; actor.prevPosY = prev.y; actor.prevPosZ = prev.z; actor.prevRotationYaw = prev.yaw; actor.prevRotationPitch = prev.pitch; actor.prevRotationYawHead = prev.yawHead; if (prev.hasBodyYaw) { actor.prevRenderYawOffset = prev.bodyYaw; } if (actor.world.isRemote) { this.applyFrameClient(actor, prev, frame); } } else if (actor instanceof EntityActor) { ((EntityActor) actor).prevRoll = prev.roll; } /* Override fall distance, apparently fallDistance gets reset * faster than RecordRecorder can record both onGround and * fallDistance being correct for player, so we just hack */ actor.fallDistance = prev.fallDistance; if (tick < this.frames.size() - 1) { Frame next = this.frames.get(tick + 1); /* Walking sounds */ if (actor instanceof EntityPlayer) { double dx = next.x - frame.x; double dy = next.y - frame.y; double dz = next.z - frame.z; actor.distanceWalkedModified = actor.distanceWalkedModified + MathHelper.sqrt(dx * dx + dz * dz) * 0.32F; actor.distanceWalkedOnStepModified = actor.distanceWalkedOnStepModified + MathHelper.sqrt(dx * dx + dy * dy + dz * dz) * 0.32F; } } } @SideOnly(Side.CLIENT) private void applyClientMovement(EntityLivingBase actor, Frame frame) { if (actor instanceof EntityPlayerSP) { MovementInput input = ((EntityPlayerSP) actor).movementInput; input.sneak = frame.isSneaking; } } @SideOnly(Side.CLIENT) private void applyFrameClient(EntityLivingBase actor, Frame prev, Frame frame) { EntityPlayerSP player = Minecraft.getMinecraft().player; if (actor == player) { CameraHandler.setRoll(prev == null ? frame.roll : prev.roll, frame.roll); } } public Frame getFrameSafe(int tick) { if (this.frames.isEmpty()) { return null; } return this.frames.get(MathUtils.clamp(tick, 0, this.frames.size() - 1)); } /** * Apply an action at the given tick on the given actor. Don't pass tick * value less than 0, otherwise you might experience game crash. */ public void applyAction(int tick, EntityLivingBase actor) { this.applyAction(tick, actor, false); } /** * Apply an action at the given tick on the given actor. Don't pass tick * value less than 0, otherwise you might experience game crash. */ public void applyAction(int tick, EntityLivingBase actor, boolean safe) { if (tick >= this.actions.size() || tick < 0) { return; } List<Action> actions = this.actions.get(tick); if (actions != null) { for (Action action : actions) { if (safe && !action.isSafe()) { continue; } try { action.apply(actor); } catch (Exception e) { e.printStackTrace(); } } } } /** * Seek the nearest morph action */ public FoundAction seekMorphAction(int tick, MorphAction last) { /* I hope it won't cause a lag... */ int threshold = 0; boolean canRet = last == null; while (tick >= threshold) { List<Action> actions = this.actions.get(tick); if (actions == null) { tick--; continue; } for (int i = actions.size() - 1; i >= 0; i--) { Action action = actions.get(i); if (!canRet && action == last) { canRet = true; } else if (canRet && action instanceof MorphAction) { ACTION.set(tick, (MorphAction) action); return ACTION; } } tick--; } return null; } /** * Apply previous morph */ public void applyPreviousMorph(EntityLivingBase actor, Replay replay, int tick, MorphType type) { boolean pause = type != MorphType.REGULAR && Blockbuster.recordPausePreview.get(); AbstractMorph replayMorph = replay == null ? null : replay.morph; /* when the tick is at the end - do not apply replay's morph - stay at the last morph */ if (tick >= this.actions.size()) return; FoundAction found = this.seekMorphAction(tick, null); if (found != null) { try { MorphAction action = found.action; if (pause && action.morph instanceof ISyncableMorph) { int foundTick = found.tick; int offset = tick - foundTick; found = this.seekMorphAction(foundTick, action); AbstractMorph previous = found == null ? replayMorph : found.action.morph; int previousOffset = foundTick - (found == null ? 0 : found.tick); action.applyWithOffset(actor, offset, previous, previousOffset, type == MorphType.FORCE); } else { action.apply(actor); } } catch (Exception e) { e.printStackTrace(); } } else if (replay != null) { if (pause && replay.morph != null) { MORPH.morph = replay.morph; MORPH.applyWithOffset(actor, tick, null, 0, type == MorphType.FORCE); } else if (type == MorphType.FORCE && replay.morph != null) { MORPH.morph = replay.morph; MORPH.applyWithForce(actor); } else { replay.apply(actor); } } } /** * Reset the actor based on this record */ public void reset(EntityLivingBase actor) { if (actor.isRiding()) { this.resetMount(actor); } if (actor.getHealth() > 0.0F) { this.applyFrame(0, actor, true); /* Reseting actor's state */ actor.setSneaking(false); actor.setSprinting(false); actor.setItemStackToSlot(EntityEquipmentSlot.HEAD, ItemStack.EMPTY); actor.setItemStackToSlot(EntityEquipmentSlot.CHEST, ItemStack.EMPTY); actor.setItemStackToSlot(EntityEquipmentSlot.LEGS, ItemStack.EMPTY); actor.setItemStackToSlot(EntityEquipmentSlot.FEET, ItemStack.EMPTY); actor.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, ItemStack.EMPTY); actor.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, ItemStack.EMPTY); } } /** * Reset actor's mount */ protected void resetMount(EntityLivingBase actor) { int index = -1; /* Find at which tick player has mounted a vehicle */ for (int i = 0, c = this.actions.size(); i < c; i++) { List<Action> actions = this.actions.get(i); if (actions == null) { continue; } for (Action action : actions) { if (action instanceof MountingAction) { MountingAction act = (MountingAction) action; if (act.isMounting) { index = i + 1; break; } } } } actor.dismountRidingEntity(); if (index != -1) { Frame frame = this.frames.get(index); if (frame != null) { Entity mount = actor.getRidingEntity(); if (mount != null && !(mount instanceof EntityActor)) { mount.setPositionAndRotation(frame.x, frame.y, frame.z, frame.yaw, frame.pitch); } } } } /** * Add an action to the record */ public void addAction(int tick, Action action) { List<Action> actions = this.actions.get(tick); if (actions != null) { actions.add(action); } else { actions = new ArrayList<Action>(); actions.add(action); this.actions.set(tick, actions); } } /** * Add an action to the recording at the specified tick and index. * If the index is greater than the frame's size at the specified tick, * the action will just be appended to the actions of the frame. * @param tick * @param index * @param action */ public void addAction(int tick, int index, Action action) { List<Action> actions = this.actions.get(tick); if (actions != null) { if (index == -1 || index > actions.size()) { actions.add(action); } else { actions.add(index, action); } } else { actions = new ArrayList<Action>(); actions.add(action); this.actions.set(tick, actions); } } /** * Adds many ticks of actions beginning at the provided fromTick. * @param tick * @param actions */ public void addActionCollection(int tick, List<List<Action>> actions) { this.addActionCollection(tick, -1, actions); } /** * Add an action collection beginning at the specified tick at the specified index. * If the index is -1, the actions at the frames will just be added on top. * @param tick * @param index can be -1 * @param actions */ public void addActionCollection(int tick, int index, List<List<Action>> actions) { if (index < -1 || tick < 0 || tick >= this.actions.size() || actions == null) { return; } for (int i = tick; i < this.actions.size() && i - tick < actions.size(); i++) { List<Action> frame = this.actions.get(i); List<Action> actionFrame = actions.get(i - tick) != null && !actions.get(i - tick).isEmpty() ? new ArrayList<>(actions.get(i - tick)) : null; if (frame == null) { this.actions.set(i, actionFrame); } else if (actionFrame != null) { if (index > frame.size() || index == -1) { frame.addAll(actionFrame); } else { frame.addAll(index, actionFrame); } } } } public void addActions(int tick, List<Action> actions) { if (tick < 0 || tick >= this.actions.size()) { return; } List<Action> present = this.actions.get(tick); if (present == null) { this.actions.set(tick, actions); } else if (actions != null) { present.addAll(actions); } } /** * Remove an action at given tick and index */ public void removeAction(int tick, int index) { if (index == -1) { this.actions.set(tick, null); } else { List<Action> actions = this.actions.get(tick); if (index >= 0 && index < actions.size()) { actions.remove(index); if (actions.isEmpty()) { this.actions.set(tick, null); } } } } public void removeActions(int fromTick, List<List<Action>> actions) { for (int tick = fromTick, c = 0; tick < this.actions.size() && c < actions.size(); tick++, c++) { if (this.actions.get(tick) != null && actions.get(c) != null) { this.actions.get(tick).removeAll(actions.get(c)); } if (this.actions.get(tick) != null && this.actions.get(tick).isEmpty()) { this.actions.set(tick, null); } } } /** * Remove actions based on the boolean mask provided. * @param fromTick * @param mask */ public void removeActionsMask(int fromTick, List<List<Boolean>> mask) { for (int tick = fromTick, c = 0; tick < this.actions.size() && c < mask.size(); tick++, c++) { if (this.actions.get(tick) != null && mask.get(c) != null) { List<Action> remove = new ArrayList<>(); for (int a = 0; a < this.actions.get(tick).size() && a < mask.get(c).size(); a++) { if (mask.get(c).get(a)) { remove.add(this.actions.get(tick).get(a)); } } this.actions.get(tick).removeAll(remove); } } } /** * Remove actions from tick and to tick inclusive and at every tick * remove from index to index inclusive. * If both index parameters are -1, all actions at the respective ticks will be deleted. * @param fromTick0 * @param toTick0 * @param fromIndex0 * @param toIndex0 */ public void removeActions(int fromTick0, int toTick0, int fromIndex0, int toIndex0) { int fromIndex = Math.min(fromIndex0, toIndex0); int toIndex = Math.max(fromIndex0, toIndex0); int fromTick = Math.min(fromTick0, toTick0); int toTick = Math.max(fromTick0, toTick0); int frameCount = this.actions.size(); if (fromIndex == -1 && toIndex == -1) { for (int tick = fromTick; tick <= toTick && tick < frameCount; tick++) { this.actions.set(tick, null); } } else { for (int tick = fromTick; tick <= toTick && tick < frameCount; tick++) { List<Action> actions = this.actions.get(tick); if (actions == null) continue; if (fromIndex != -1 && toIndex != -1) { int max = toIndex; while (fromIndex <= max && fromIndex < actions.size()) { actions.remove(fromIndex); max--; } } else { int index = fromIndex == -1 ? toIndex : fromIndex; if (index < actions.size()) { actions.remove(index); } } if (actions.isEmpty()) { this.actions.set(tick, null); } } } } /** * Replace an action at given tick and index */ public void replaceAction(int tick, int index, Action action) { if (tick < 0 || tick >= this.actions.size()) { return; } List<Action> actions = this.actions.get(tick); if (actions == null || index < 0 || index >= actions.size()) { this.addAction(tick, action); } else { actions.set(index, action); } } /** * Create a copy of this record */ @Override public Record clone() { Record record = new Record(this.filename); record.version = this.version; record.preDelay = this.preDelay; record.postDelay = this.postDelay; for (Frame frame : this.frames) { record.frames.add(frame.copy()); } for (List<Action> actions : this.actions) { if (actions == null || actions.isEmpty()) { record.actions.add(null); } else { List<Action> newActions = new ArrayList<Action>(); for (Action action : actions) { try { NBTTagCompound tag = new NBTTagCompound(); action.toNBT(tag); Action newAction = ActionRegistry.fromType(ActionRegistry.getType(action)); newAction.fromNBT(tag); newActions.add(newAction); } catch (Exception e) { System.out.println("Failed to clone an action!"); e.printStackTrace(); } } record.actions.add(newActions); } } return record; } public void save(File file) throws IOException { this.save(file, true); } /** * Save a recording to given file. * * This method basically writes the signature of the current version, * and then saves all available frames and actions. */ public void save(File file, boolean savePast) throws IOException { if (savePast && file.isFile()) { this.savePastCopies(file); } NBTTagCompound compound = new NBTTagCompound(); NBTTagList frames = new NBTTagList(); /* Version of the recording */ compound.setShort("Version", SIGNATURE); compound.setInteger("PreDelay", this.preDelay); compound.setInteger("PostDelay", this.postDelay); compound.setTag("Actions", this.createActionMap()); if (this.playerData != null) { compound.setTag("PlayerData", this.playerData); } int c = this.frames.size(); int d = this.actions.size() - this.frames.size(); if (d < 0) d = 0; for (int i = 0; i < c; i++) { NBTTagCompound frameTag = new NBTTagCompound(); Frame frame = this.frames.get(i); List<Action> actions = null; if (d + i <= this.actions.size() - 1) { actions = this.actions.get(d + i); } frame.toNBT(frameTag); if (actions != null) { NBTTagList actionsTag = new NBTTagList(); for (Action action : actions) { NBTTagCompound actionTag = new NBTTagCompound(); action.toNBT(actionTag); actionTag.setByte("Type", ActionRegistry.CLASS_TO_ID.get(action.getClass())); actionsTag.appendTag(actionTag); } frameTag.setTag("Action", actionsTag); } frames.appendTag(frameTag); } compound.setTag("Frames", frames); CompressedStreamTools.writeCompressed(compound, new FileOutputStream(file)); } /** * This method removes the last file, and renames past versions of a recording files. * This should save countless hours of work in case somebody accidentally overwrote * a player recording. */ private void savePastCopies(File file) { final int copies = 5; int counter = copies; String name = FilenameUtils.removeExtension(file.getName()); while (counter >= 0 && file.exists()) { File current = this.getPastFile(file, name, counter); if (current.exists()) { if (counter == copies) { current.delete(); } else { File previous = this.getPastFile(file, name, counter + 1); current.renameTo(previous); } } counter--; } } /** * Get a path to the past copy of the file */ private File getPastFile(File file, String name, int iteration) { return new File(file.getParentFile(), name + (iteration == 0 ? ".dat" : ".dat~" + iteration)); } /** * Creates an action map between action name and an action type byte values * for compatibility */ private NBTTagCompound createActionMap() { NBTTagCompound tag = new NBTTagCompound(); for (Map.Entry<String, Byte> entry : ActionRegistry.NAME_TO_ID.entrySet()) { tag.setString(entry.getValue().toString(), entry.getKey()); } return tag; } /** * Read a recording from given file. * * This method basically checks if the given file has appropriate short * signature, and reads all frames and actions from the file. */ public void load(File file) throws IOException { this.load(CompressedStreamTools.readCompressed(new FileInputStream(file))); } public void load(NBTTagCompound compound) { NBTTagCompound map = null; this.version = compound.getShort("Version"); this.preDelay = compound.getInteger("PreDelay"); this.postDelay = compound.getInteger("PostDelay"); if (compound.hasKey("Actions", 10)) { map = compound.getCompoundTag("Actions"); } if (compound.hasKey("PlayerData", 10)) { this.playerData = compound.getCompoundTag("PlayerData"); } NBTTagList frames = (NBTTagList) compound.getTag("Frames"); for (int i = 0, c = frames.tagCount(); i < c; i++) { NBTTagCompound frameTag = frames.getCompoundTagAt(i); NBTBase actionTag = frameTag.getTag("Action"); Frame frame = new Frame(); frame.fromNBT(frameTag); if (actionTag != null) { try { List<Action> actions = new ArrayList<Action>(); if (actionTag instanceof NBTTagCompound) { Action action = this.actionFromNBT((NBTTagCompound) actionTag, map); if (action != null) { actions.add(action); } } else if (actionTag instanceof NBTTagList) { NBTTagList list = (NBTTagList) actionTag; for (int ii = 0, cc = list.tagCount(); ii < cc; ii++) { Action action = this.actionFromNBT(list.getCompoundTagAt(ii), map); if (action != null) { actions.add(action); } } } this.actions.add(actions); } catch (Exception e) { System.out.println("Failed to load an action at frame " + i); e.printStackTrace(); } } else { this.actions.add(null); } this.frames.add(frame); } } private Action actionFromNBT(NBTTagCompound tag, NBTTagCompound map) throws Exception { byte type = tag.getByte("Type"); Action action = null; if (map == null) { action = ActionRegistry.fromType(type); } else { String name = map.getString(String.valueOf(type)); if (ActionRegistry.NAME_TO_CLASS.containsKey(name)) { action = ActionRegistry.fromName(name); } } if (action != null) { action.fromNBT(tag); } return action; } public void reverse() { Collections.reverse(this.frames); Collections.reverse(this.actions); } public void fillMissingActions() { while (this.actions.size() < this.frames.size()) { this.actions.add(null); } } public static class FoundAction { public int tick; public MorphAction action; public void set(int tick, MorphAction action) { this.tick = tick; this.action = action; } } public static enum MorphType { REGULAR, PAUSE, FORCE } }
37,250
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Frame.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/data/Frame.java
package mchorse.blockbuster.recording.data; import io.netty.buffer.ByteBuf; import mchorse.blockbuster.aperture.CameraHandler; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.blockbuster.recording.scene.Replay; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.datasync.DataParameter; import net.minecraft.util.EnumHand; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Type; /** * Recording frame class * * This class stores state data about the player in the specific frame that was * captured. */ public class Frame { public static DataParameter<Byte> FLAGS; /* Position */ public double x; public double y; public double z; /* Rotation */ public float yaw; public float yawHead; public float pitch; public boolean hasBodyYaw; public float bodyYaw; /* Mount's data */ public float mountYaw; public float mountPitch; public boolean isMounted; /* Motion */ public double motionX; public double motionY; public double motionZ; /* Fall distance */ public float fallDistance; /* Entity flags */ public boolean isAirBorne; public boolean isSneaking; public boolean isSprinting; public boolean onGround; public boolean flyingElytra; /* Client data */ public float roll; /* Active hand */ public int activeHands; private int hotbarSlot; private int foodLevel; private int totalExperience; /* Methods for retrieving/applying state data */ /** * Set frame fields from player entity. */ public void fromPlayer(EntityPlayer player) { Entity mount = player.isRiding() ? player.getRidingEntity() : player; /* Position and rotation */ this.x = mount.posX; this.y = player.isRiding() && player.getRidingEntity().posY > player.posY ? player.posY : mount.posY; this.z = mount.posZ; this.yaw = player.rotationYaw; this.yawHead = player.rotationYawHead; this.pitch = player.rotationPitch; this.hasBodyYaw = true; this.bodyYaw = player.renderYawOffset; /* Mount information */ this.isMounted = mount != player; if (this.isMounted) { this.mountYaw = mount.rotationYaw; this.mountPitch = mount.rotationPitch; } /* Motion and fall distance */ this.motionX = mount.motionX; this.motionY = mount.motionY; this.motionZ = mount.motionZ; this.fallDistance = mount.fallDistance; /* States */ this.isSprinting = mount.isSprinting(); this.isSneaking = player.isSneaking(); this.flyingElytra = player.isElytraFlying(); this.isAirBorne = mount.isAirBorne; this.onGround = mount.onGround; /* Active hands */ this.activeHands = player.isHandActive() ? (player.getActiveHand() == EnumHand.OFF_HAND ? 2 : 1) : 0; if (player.world.isRemote) { this.fromPlayerClient(player); } this.hotbarSlot = player.inventory.currentItem; this.foodLevel = player.getFoodStats().getFoodLevel(); this.totalExperience = player.experienceTotal; } @SideOnly(Side.CLIENT) private void fromPlayerClient(EntityPlayer player) { EntityPlayerSP local = Minecraft.getMinecraft().player; if (player == local) { this.roll = CameraHandler.getRoll(); } } /** * Apply frame properties on actor. Different actions will be made * depending on which side this method was invoked. * * Use second argument to force things to be cool. */ public void apply(EntityLivingBase actor, boolean force) { this.apply(actor, null, force); } /** * * @param actor * @param replay the replay that is being used for this record - used for playback configuration * @param force */ public void apply(EntityLivingBase actor, @Nullable Replay replay, boolean force) { boolean isRemote = actor.world.isRemote; Entity mount = actor.isRiding() ? actor.getRidingEntity() : actor; if (mount instanceof EntityActor) { mount = actor; } if (actor instanceof EntityActor) { EntityActor theActor = (EntityActor) actor; theActor.isMounted = this.isMounted; theActor.roll = this.roll; } /* This is most important part of the code that makes the recording * super smooth. * * By the way, this code is useful only on the client side, for more * reference see renderer classes (they use prev* and lastTick* stuff * for interpolation). */ if (this.isMounted) { mount.prevRotationYaw = mount.rotationYaw; mount.prevRotationPitch = mount.rotationPitch; } actor.prevRotationYaw = actor.rotationYaw; actor.prevRotationPitch = actor.rotationPitch; actor.prevRotationYawHead = actor.rotationYawHead; /* Inject frame's values into actor */ if (!isRemote || force) { mount.setPosition(this.x, this.y, this.z); } /* Rotation */ if (isRemote || force) { if (this.isMounted) { mount.rotationYaw = this.mountYaw; mount.rotationPitch = this.mountPitch; if (actor == mount) { actor.setPosition(this.x, this.y, this.z); } } actor.rotationYaw = this.yaw; actor.rotationPitch = this.pitch; actor.rotationYawHead = this.yawHead; } /* Motion and fall distance */ mount.motionX = this.motionX; mount.motionY = this.motionY; mount.motionZ = this.motionZ; mount.fallDistance = this.fallDistance; /* Booleans */ if (!isRemote || force) { mount.setSprinting(this.isSprinting); actor.setSneaking(this.isSneaking); this.setFlag(actor, 7, this.flyingElytra); } mount.isAirBorne = this.isAirBorne; mount.onGround = this.onGround; if (!isRemote) { if (this.activeHands > 0 && !actor.isHandActive()) { actor.setActiveHand(this.activeHands == 1 ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND); } else if (this.activeHands == 0 && actor.isHandActive()) { actor.stopActiveHand(); } } if (actor instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) actor; player.inventory.currentItem = this.hotbarSlot; if (replay != null && replay.playBackXPFood) { player.getFoodStats().setFoodLevel(this.foodLevel); player.addExperience(this.totalExperience - player.experienceTotal); } } } /** * Set entity flags... if only vanilla could expose that shit */ private void setFlag(EntityLivingBase actor, int i, boolean flag) { if (FLAGS == null) { Field field = null; for (Field f : Entity.class.getDeclaredFields()) { int mod = f.getModifiers(); Type type = f.getGenericType(); if (Modifier.isProtected(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod) && f.getType() == DataParameter.class) { field = f; break; } } if (field != null) { try { field.setAccessible(true); FLAGS = (DataParameter<Byte>) field.get(null); } catch (Exception e) {} } } if (FLAGS != null) { byte flags = actor.getDataManager().get(FLAGS).byteValue(); actor.getDataManager().set(FLAGS, (byte) (flag ? flags | (1 << i) : flags & ~(1 << i))); } } /** * Create a copy of this frame */ public Frame copy() { Frame frame = new Frame(); frame.x = this.x; frame.y = this.y; frame.z = this.z; frame.yaw = this.yaw; frame.yawHead = this.yawHead; frame.pitch = this.pitch; frame.hasBodyYaw = this.hasBodyYaw; frame.bodyYaw = this.bodyYaw; frame.isMounted = this.isMounted; if (frame.isMounted) { frame.mountYaw = this.mountYaw; frame.mountPitch = this.mountPitch; } frame.motionX = this.motionX; frame.motionY = this.motionY; frame.motionZ = this.motionZ; frame.fallDistance = this.fallDistance; frame.isAirBorne = this.isAirBorne; frame.isSneaking = this.isSneaking; frame.isSprinting = this.isSprinting; frame.onGround = this.onGround; frame.flyingElytra = this.flyingElytra; frame.activeHands = this.activeHands; frame.roll = this.roll; frame.hotbarSlot = this.hotbarSlot; frame.foodLevel = this.foodLevel; frame.totalExperience = this.totalExperience; return frame; } /* Save/load frame instance */ public void toBytes(ByteBuf buf) { buf.writeDouble(this.x); buf.writeDouble(this.y); buf.writeDouble(this.z); buf.writeFloat(this.yaw); buf.writeFloat(this.yawHead); buf.writeFloat(this.pitch); buf.writeBoolean(this.hasBodyYaw); if (this.hasBodyYaw) { buf.writeFloat(this.bodyYaw); } buf.writeBoolean(this.isMounted); if (this.isMounted) { buf.writeFloat(this.mountYaw); buf.writeFloat(this.mountPitch); } buf.writeFloat((float) this.motionX); buf.writeFloat((float) this.motionY); buf.writeFloat((float) this.motionZ); buf.writeFloat(this.fallDistance); buf.writeBoolean(this.isAirBorne); buf.writeBoolean(this.isSneaking); buf.writeBoolean(this.isSprinting); buf.writeBoolean(this.onGround); buf.writeBoolean(this.flyingElytra); buf.writeByte(this.activeHands); buf.writeFloat(this.roll); buf.writeInt(this.hotbarSlot); buf.writeInt(this.foodLevel); buf.writeInt(this.totalExperience); } public void fromBytes(ByteBuf buf) { this.x = buf.readDouble(); this.y = buf.readDouble(); this.z = buf.readDouble(); this.yaw = buf.readFloat(); this.yawHead = buf.readFloat(); this.pitch = buf.readFloat(); if (buf.readBoolean()) { this.hasBodyYaw = true; this.bodyYaw = buf.readFloat(); } this.isMounted = buf.readBoolean(); if (this.isMounted) { this.mountYaw = buf.readFloat(); this.mountPitch = buf.readFloat(); } this.motionX = buf.readFloat(); this.motionY = buf.readFloat(); this.motionZ = buf.readFloat(); this.fallDistance = buf.readFloat(); this.isAirBorne = buf.readBoolean(); this.isSneaking = buf.readBoolean(); this.isSprinting = buf.readBoolean(); this.onGround = buf.readBoolean(); this.flyingElytra = buf.readBoolean(); this.activeHands = buf.readByte(); this.roll = buf.readFloat(); this.hotbarSlot = buf.readInt(); this.foodLevel = buf.readInt(); this.totalExperience = buf.readInt(); } /** * Write frame data to NBT tag. Used for saving the frame on the disk. * * This is probably going to be extracted in the future to support * compatibility, but I don't really know since writing the data happens * in one format, while reading is in different versions. */ public void toNBT(NBTTagCompound tag) { tag.setDouble("X", this.x); tag.setDouble("Y", this.y); tag.setDouble("Z", this.z); tag.setFloat("MX", (float) this.motionX); tag.setFloat("MY", (float) this.motionX); tag.setFloat("MZ", (float) this.motionX); tag.setFloat("RX", this.yaw); tag.setFloat("RY", this.pitch); tag.setFloat("RZ", this.yawHead); if (this.hasBodyYaw) { tag.setFloat("RW", this.bodyYaw); } if (this.isMounted) { tag.setFloat("MRX", this.mountYaw); tag.setFloat("MRY", this.mountPitch); } tag.setFloat("Fall", this.fallDistance); tag.setBoolean("Airborne", this.isAirBorne); tag.setBoolean("Elytra", this.flyingElytra); tag.setBoolean("Sneaking", this.isSneaking); tag.setBoolean("Sprinting", this.isSprinting); tag.setBoolean("Ground", this.onGround); if (this.activeHands > 0) { tag.setByte("Hands", (byte) this.activeHands); } if (this.roll != 0) { tag.setFloat("Roll", this.roll); } tag.setInteger("HotbarSlot", this.hotbarSlot); tag.setInteger("FoodLevel", this.foodLevel); tag.setInteger("TotalExperience", this.totalExperience); } /** * Read frame data from NBT tag. Used for loading frame from disk. * * This is going to be extracted in the future to support compatibility. */ public void fromNBT(NBTTagCompound tag) { this.x = tag.getDouble("X"); this.y = tag.getDouble("Y"); this.z = tag.getDouble("Z"); this.motionX = tag.getFloat("MX"); this.motionY = tag.getFloat("MY"); this.motionZ = tag.getFloat("MZ"); this.yaw = tag.getFloat("RX"); this.pitch = tag.getFloat("RY"); this.yawHead = tag.getFloat("RZ"); if (tag.hasKey("RW")) { this.hasBodyYaw = true; this.bodyYaw = tag.getFloat("RW"); } if (tag.hasKey("MRX") && tag.hasKey("MRY")) { this.isMounted = true; this.mountYaw = tag.getFloat("MRX"); this.mountPitch = tag.getFloat("MRY"); } this.fallDistance = tag.getFloat("Fall"); this.isAirBorne = tag.getBoolean("Airborne"); this.flyingElytra = tag.getBoolean("Elytra"); this.isSneaking = tag.getBoolean("Sneaking"); this.isSprinting = tag.getBoolean("Sprinting"); this.onGround = tag.getBoolean("Ground"); if (tag.hasKey("Hands")) { this.activeHands = tag.getByte("Hands"); } if (tag.hasKey("Roll")) { this.roll = tag.getFloat("Roll"); } this.hotbarSlot = tag.hasKey("HotbarSlot") ? tag.getInteger("HotbarSlot") : this.hotbarSlot; this.foodLevel = tag.hasKey("FoodLevel") ? tag.getInteger("FoodLevel") : this.foodLevel; this.totalExperience = tag.hasKey("TotalExperience") ? tag.getInteger("TotalExperience") : this.totalExperience; } public enum RotationChannel { HEAD_YAW, HEAD_PITCH, BODY_YAW } }
15,943
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
SceneManager.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/scene/SceneManager.java
package mchorse.blockbuster.recording.scene; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.recording.Utils; import mchorse.blockbuster.recording.data.Mode; import mchorse.mclib.utils.Patterns; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; /** * Scene manager * * This bro allows to manage scenes (those are something like remote director blocks). */ public class SceneManager { /** * Currently loaded scenes */ private Map<String, Scene> scenes = new ConcurrentHashMap<String, Scene>(); private List<String> toRemove = new ArrayList<String>(); private Map<String, Scene> toPut = new HashMap<String, Scene>(); private boolean ticking; public Map<String, Scene> getScenes() { return new HashMap<>(this.scenes); } public static boolean isValidFilename(String filename) { return !filename.isEmpty() && Patterns.FILENAME.matcher(filename).matches(); } /** * Reset scene manager */ public void reset() { this.ticking = false; this.toRemove.clear(); this.toPut.clear(); this.scenes.clear(); } /** * Spawn actors and execute unsafe actions */ public void worldTick(World world) { for (Map.Entry<String, Scene> entry : this.scenes.entrySet()) { Scene scene = entry.getValue(); scene.worldTick(world); } } /** * Tick scenes */ public void tick() { this.ticking = true; try { for (Map.Entry<String, Scene> entry : this.scenes.entrySet()) { Scene scene = entry.getValue(); scene.tick(); if (!scene.playing) { this.toRemove.add(entry.getKey()); } } } catch (Exception e) { e.printStackTrace(); } this.ticking = false; for (String scene : this.toRemove) { this.scenes.remove(scene); } this.scenes.putAll(this.toPut); this.toRemove.clear(); this.toPut.clear(); } /** * Play a scene */ public boolean play(String filename, World world) { Scene scene = this.get(filename,world); if (scene == null) { return false; } scene.startPlayback(0); return true; } public void record(String filename, String record, EntityPlayerMP player) { this.record(filename, record, 0, player); } /** * Record the player */ public void record(String filename, String record, int offset, EntityPlayerMP player) { final Scene scene = this.get(filename, player.world); if (scene != null) { scene.setWorld(player.world); final Replay replay = scene.getByFile(record); if (replay != null) { CommonProxy.manager.record(replay.id, player, Mode.ACTIONS, replay.teleportBack, true, offset, () -> { if (!CommonProxy.manager.recorders.containsKey(player)) { this.put(filename, scene); scene.startPlayback(record, offset); } else { scene.stopPlayback(true); } replay.apply(player); }); } } } /** * Toggle playback of a scene by given filename */ public boolean toggle(String filename, World world) { Scene scene = this.scenes.get(filename); if (scene != null) { scene.stopPlayback(true); return false; } return this.play(filename, world); } /** * Get currently running or load a scene */ public Scene get(String filename, World world) { Scene scene = this.scenes.get(filename); if (scene != null) { return scene; } try { scene = this.load(filename); if (scene != null) { scene.setWorld(world); scene.setSender(new SceneSender(scene)); this.put(filename, scene); } } catch (Exception e) { e.printStackTrace(); } return scene; } /** * Load a scene by given filename */ public Scene load(String filename) throws IOException { File file = sceneFile(filename); if (!file.isFile()) { return null; } NBTTagCompound compound = CompressedStreamTools.readCompressed(new FileInputStream(file)); Scene scene = new Scene(); scene.setId(filename); scene.fromNBT(compound); return scene; } public void save(String filename, Scene scene) throws IOException { this.save(filename, scene, Blockbuster.sceneSaveUpdate.get()); } /** * Save a scene by given filename */ public void save(String filename, Scene scene, boolean reload) throws IOException { Scene present = this.scenes.get(scene.getId()); if (reload && present != null) { present.copy(scene); present.reload(present.getCurrentTick()); } File file = sceneFile(filename); NBTTagCompound compound = new NBTTagCompound(); scene.toNBT(compound); CompressedStreamTools.writeCompressed(compound, new FileOutputStream(file)); } /** * Rename a scene on the disk */ public boolean rename(String from, String to) { File fromFile = sceneFile(from); File toFile = sceneFile(to); if (fromFile.isFile() && !toFile.exists()) { return fromFile.renameTo(toFile); } return false; } /** * Remove a scene from the disk */ public boolean remove(String filename) { File file = sceneFile(filename); if (file.exists()) { return file.delete(); } return false; } /** * Returns a file instance to the scene by given filename */ private File sceneFile(String filename) { return Utils.serverFile("blockbuster/scenes", filename); } private void put(String filename, Scene scene) { (this.ticking ? this.toPut : this.scenes).put(filename, scene); } /** * Get all the NBT files in the scenes folder */ public List<String> sceneFiles() { return Utils.serverFiles("blockbuster/scenes"); } }
7,317
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Replay.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/scene/Replay.java
package mchorse.blockbuster.recording.scene; import com.google.common.base.Objects; import io.netty.buffer.ByteBuf; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.mclib.utils.TextUtils; import mchorse.metamorph.api.MorphAPI; import mchorse.metamorph.api.MorphManager; import mchorse.metamorph.api.MorphUtils; import mchorse.metamorph.api.morphs.AbstractMorph; import mchorse.vanilla_pack.morphs.PlayerMorph; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.network.ByteBufUtils; /** * Replay domain object * * This class is responsible for storing, and persisting to different sources * (to NBT and ByteBuf) its content. */ public class Replay { /* Meta data */ public String id = ""; public String name = ""; public String target = ""; public boolean invincible = false; public boolean enableBurning = true; public boolean teleportBack = true; /** * Whether the food and XP recording should be played back */ public boolean playBackXPFood = false; /* Visual data */ public AbstractMorph morph; public boolean invisible = false; public boolean enabled = true; public boolean fake = false; public float health = 20F; public boolean renderLast = false; public int foodLevel = 20; public int totalExperience = 0; public Replay() {} public Replay(String id) { this.id = id; } /** * Apply replay on an entity */ public void apply(EntityLivingBase entity) { if (entity instanceof EntityActor) { this.apply((EntityActor) entity); } else if (entity instanceof EntityPlayer) { if (!(this.morph instanceof PlayerMorph)) { this.apply((EntityPlayer) entity); } } } /** * Apply replay on an actor */ public void apply(EntityActor actor) { String name = TextUtils.processColoredText(this.name); actor.setCustomNameTag(name); actor.setEntityInvulnerable(this.invincible); actor.morph(mchorse.metamorph.api.MorphUtils.copy(this.morph), false); actor.invisible = this.invisible; actor.enableBurning = this.enableBurning; if (this.health > 20) { actor.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(this.health); } actor.setHealth(this.health); actor.renderLast = this.renderLast; actor.notifyPlayers(); } /** * Apply replay on a player */ public void apply(EntityPlayer player) { MorphAPI.morph(player, mchorse.metamorph.api.MorphUtils.copy(this.morph), true); player.setHealth(this.health); player.getFoodStats().setFoodLevel(this.foodLevel); player.experienceTotal = 0; player.experience = 0; player.experienceLevel = 0; this.setExperienceWithoutSound(player, this.totalExperience); } private void setExperienceWithoutSound(EntityPlayer player, int amount) { /* copied from EntityPlayer.addExperience(int) and modified */ player.addScore(amount); int i = Integer.MAX_VALUE - player.experienceTotal; if (amount > i) { amount = i; } player.experience += (float)amount / (float)player.xpBarCap(); for (player.experienceTotal += amount; player.experience >= 1.0F; player.experience /= (float)player.xpBarCap()) { player.experience = (player.experience - 1.0F) * (float)player.xpBarCap(); player.experienceLevel += 1; } } /* to / from NBT */ public void toNBT(NBTTagCompound tag) { tag.setString("Id", this.id); tag.setString("Name", this.name); tag.setString("Target", this.target); if (this.morph != null) { tag.setTag("Morph", this.morph.toNBT()); } tag.setBoolean("Invincible", this.invincible); tag.setBoolean("Invisible", this.invisible); tag.setBoolean("EnableBurning", this.enableBurning); tag.setBoolean("Enabled", this.enabled); tag.setBoolean("Fake", this.fake); if (!this.teleportBack) tag.setBoolean("TP", this.teleportBack); if (this.health != 20) tag.setFloat("Health", this.health); if (this.foodLevel != 20) tag.setInteger("FoodLevel", this.foodLevel); if (this.totalExperience != 0) tag.setInteger("TotalExperience", this.totalExperience); if (this.renderLast) tag.setBoolean("RenderLast", this.renderLast); if (this.playBackXPFood) tag.setBoolean("PlaybackXPFoodLevel", this.playBackXPFood); } public void fromNBT(NBTTagCompound tag) { this.id = tag.getString("Id"); this.name = tag.getString("Name"); this.target = tag.getString("Target"); this.morph = MorphManager.INSTANCE.morphFromNBT(tag.getCompoundTag("Morph")); this.invincible = tag.getBoolean("Invincible"); this.invisible = tag.getBoolean("Invisible"); this.enableBurning = tag.getBoolean("EnableBurning"); this.fake = tag.getBoolean("Fake"); this.foodLevel = tag.hasKey("FoodLevel") ? tag.getInteger("FoodLevel") : this.foodLevel; this.totalExperience = tag.hasKey("TotalExperience") ? tag.getInteger("TotalExperience") : this.totalExperience; if (tag.hasKey("Enabled")) this.enabled = tag.getBoolean("Enabled"); if (tag.hasKey("TP")) this.teleportBack = tag.getBoolean("TP"); if (tag.hasKey("Health")) this.health = tag.getFloat("Health"); if (tag.hasKey("RenderLast")) this.renderLast = tag.getBoolean("RenderLast"); if (tag.hasKey("PlaybackXPFoodLevel")) this.playBackXPFood = tag.getBoolean("PlaybackXPFoodLevel"); } /* to / from ByteBuf */ public void toBuf(ByteBuf buf) { ByteBufUtils.writeUTF8String(buf, this.id); ByteBufUtils.writeUTF8String(buf, this.name); ByteBufUtils.writeUTF8String(buf, this.target); MorphUtils.morphToBuf(buf, this.morph); buf.writeBoolean(this.invincible); buf.writeBoolean(this.invisible); buf.writeBoolean(this.enableBurning); buf.writeBoolean(this.enabled); buf.writeBoolean(this.fake); buf.writeBoolean(this.teleportBack); buf.writeBoolean(this.renderLast); buf.writeFloat(this.health); buf.writeInt(this.foodLevel); buf.writeInt(this.totalExperience); buf.writeBoolean(this.playBackXPFood); } public void fromBuf(ByteBuf buf) { this.id = ByteBufUtils.readUTF8String(buf); this.name = ByteBufUtils.readUTF8String(buf); this.target = ByteBufUtils.readUTF8String(buf); this.morph = MorphUtils.morphFromBuf(buf); this.invincible = buf.readBoolean(); this.invisible = buf.readBoolean(); this.enableBurning = buf.readBoolean(); this.enabled = buf.readBoolean(); this.fake = buf.readBoolean(); this.teleportBack = buf.readBoolean(); this.renderLast = buf.readBoolean(); this.health = buf.readFloat(); this.foodLevel = buf.readInt(); this.totalExperience = buf.readInt(); this.playBackXPFood = buf.readBoolean(); } @Override public boolean equals(Object obj) { if (obj instanceof Replay) { Replay replay = (Replay) obj; return Objects.equal(replay.id, this.id) && Objects.equal(replay.name, this.name) && Objects.equal(replay.target, this.target) && replay.invincible == this.invincible && replay.invisible == this.invisible && replay.enableBurning == this.enableBurning && replay.renderLast == this.renderLast && Objects.equal(replay.morph, this.morph); } return super.equals(obj); } public Replay copy() { Replay replay = new Replay(); replay.id = this.id; replay.name = this.name; replay.target = this.target; replay.morph = mchorse.metamorph.api.MorphUtils.copy(this.morph); replay.invincible = this.invincible; replay.invisible = this.invisible; replay.enableBurning = this.enableBurning; replay.enabled = this.enabled; replay.fake = this.fake; replay.teleportBack = this.teleportBack; replay.renderLast = this.renderLast; replay.health = this.health; replay.foodLevel = this.foodLevel; replay.totalExperience = this.totalExperience; replay.playBackXPFood = this.playBackXPFood; return replay; } }
8,981
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
SceneSender.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/scene/SceneSender.java
package mchorse.blockbuster.recording.scene; import net.minecraft.command.CommandResultStats; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; public class SceneSender implements ICommandSender { public Scene scene; public SceneSender(Scene scene) { this.scene = scene; } @Override public String getName() { return "SceneSender(" + this.scene.getId() + ")"; } @Override public ITextComponent getDisplayName() { return new TextComponentString(this.getName()); } @Override public void sendMessage(ITextComponent component) {} @Override public boolean canUseCommand(int permLevel, String commandName) { return true; } @Override public BlockPos getPosition() { return BlockPos.ORIGIN; } @Override public Vec3d getPositionVector() { return new Vec3d(this.getPosition()); } @Override public World getEntityWorld() { return this.scene.getWorld(); } @Override public Entity getCommandSenderEntity() { return null; } @Override public boolean sendCommandFeedback() { return false; } @Override public void setCommandStat(CommandResultStats.Type type, int amount) {} @Override public MinecraftServer getServer() { return this.scene.getWorld().getMinecraftServer(); } }
1,715
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z
Scene.java
/FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/recording/scene/Scene.java
package mchorse.blockbuster.recording.scene; import com.mojang.authlib.GameProfile; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import mchorse.blockbuster.Blockbuster; import mchorse.blockbuster.CommonProxy; import mchorse.blockbuster.audio.AudioHandler; import mchorse.blockbuster.audio.AudioState; import mchorse.blockbuster.capabilities.recording.IRecording; import mchorse.blockbuster.capabilities.recording.Recording; import mchorse.blockbuster.common.entity.EntityActor; import mchorse.blockbuster.recording.RecordPlayer; import mchorse.blockbuster.recording.RecordUtils; import mchorse.blockbuster.recording.data.Mode; import mchorse.blockbuster.recording.data.Record; import mchorse.blockbuster.recording.scene.fake.FakeContext; import mchorse.mclib.utils.LatencyTimer; import mchorse.vanilla_pack.morphs.PlayerMorph; import net.minecraft.command.ICommandSender; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.EnumPacketDirection; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.NetworkManager; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.CPacketClientSettings; import net.minecraft.scoreboard.Team; import net.minecraft.server.management.PlayerInteractionManager; import net.minecraft.server.management.PlayerList; import net.minecraft.util.EnumHandSide; import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.fml.common.network.ByteBufUtils; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Scene */ public class Scene { public static long lastUpdate; /** * Pattern for finding numbered suffix */ public static final Pattern NUMBERED_SUFFIX = Pattern.compile("_(\\d+)$"); /** * Pattern for finding prefix */ public static final Pattern PREFIX = Pattern.compile("^(.+)_([^_]+)$"); /** * Pattern for finding indexes */ public static final Pattern INDEXES = Pattern.compile("[^_]+"); /** * Scene's id/filename */ private String id = ""; /** * List of replays */ public List<Replay> replays = new ArrayList<Replay>(); /** * Display title, used for client organization purposes */ public String title = ""; /** * Command which should be executed when director block starts * playing */ public String startCommand = ""; /** * Command which should be executed when director block stops * playing */ public String stopCommand = ""; /** * Whether director's playback is looping */ public boolean loops; private AudioHandler audioHandler = new AudioHandler(); /* Runtime properties */ /** * Whether this scene is active */ public boolean playing; /** * Map of currently playing actors */ public Map<Replay, RecordPlayer> actors = new HashMap<Replay, RecordPlayer>(); /** * Count of actors which were spawned (used to check whether actors * are still playing) */ public int actorsCount = 0; /** * Director command sender */ private ICommandSender sender; /** * This tick used for checking if actors still playing */ private int tick = 0; /** * Whether this scene gets recorded */ private boolean wasRecording; /** * Whether it's paused */ private boolean paused; /** * World instance */ private World world; /** * List that contains the players that have been chosen for first person playback in this scene * with their inventory before playback has been started */ private List<PlayerState> targetPlayers = new ArrayList<>(); /** * * @param player * @return true if the given player reference has been chosen for first person playback in one actor */ public boolean isPlayerTargetPlayback(EntityPlayer player) { for (PlayerState state : this.targetPlayers) { if (state.getPlayer() == player) { return true; } } return false; } public List<EntityPlayer> getTargetPlaybackPlayers() { List<EntityPlayer> players = new ArrayList<>(); for (PlayerState state : this.targetPlayers) { players.add(state.getPlayer()); } return players; } public String getAudio() { return this.audioHandler.getAudioName(); } public void setAudio(String audio) { this.audioHandler.setAudioName(audio); } /** * Audio shift */ public int getAudioShift() { return this.audioHandler.getAudioShift(); } public void setAudioShift(int audioShift) { this.audioHandler.setAudioShift(audioShift); /* update the audio on the server so the shift change is visible */ if (this.world != null && !this.world.isRemote) { this.audioHandler.goTo(this.tick); } } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public void setWorld(World world) { this.world = world; } public World getWorld() { return this.world; } public int getTick() { return this.tick; } public int getCurrentTick() { for (RecordPlayer player : this.actors.values()) { if (!player.isFinished() && !player.actor.isDead) { return player.tick; } } return 0; } public AudioState getAudioState() { return this.audioHandler.getAudioState(); } /** * Set director command sender */ public void setSender(ICommandSender sender) { this.sender = sender; } /** * Get a replay by actor. Comparison is based on actor's UUID. */ public Replay getByFile(String filename) { for (Replay replay : this.replays) { if (replay.id.equals(filename)) { return replay; } } return null; } /** * Get maximum length of current director block */ public int getMaxLength() { int max = 0; for (Replay replay : this.replays) { Record record = null; try { record = CommonProxy.manager.get(replay.id); } catch (Exception e) {} if (record != null) { max = Math.max(max, record.getFullLength()); } } return max; } public void tick() { if (Blockbuster.debugPlaybackTicks.get()) { this.logTicks(); } for (RecordPlayer player : this.actors.values()) { if (!player.realPlayer && player.actor instanceof EntityPlayer) { ((EntityPlayerMP) player.actor).onUpdateEntity(); } else if (!player.actorUpdated) { player.next(); } player.actorUpdated = false; } if (this.playing && !this.paused) { if (this.tick % 4 == 0 && !this.checkActors()) return; this.audioHandler.update(); this.tick++; } } public void worldTick(World world) { for (RecordPlayer player : this.actors.values()) { if (player.actor.world == world) { if (this.playing) { player.checkAndSpawn(); } player.playActions(); } } } /** * Check whether collected actors are still playing */ public boolean areActorsFinished() { int count = 0; for (Map.Entry<Replay, RecordPlayer> entry : this.actors.entrySet()) { Replay replay = entry.getKey(); RecordPlayer actor = entry.getValue(); if (this.loops && actor.isFinished()) { actor.record.reset(actor.actor); actor.startPlaying(replay.id, actor.kill); actor.record.applyAction(0, actor.actor); CommonProxy.manager.players.put(actor.actor, actor); } if ((actor.isFinished() && actor.playing) || actor.actor.isDead) { count++; } } return count == this.actorsCount; } /* Playback and editing */ /** * Check whether actors are still playing, if they're stop the whole * thing * @return false if every actor is finished and the scene can be stopped. */ public boolean checkActors() { /* * don't stop the entire scene when one actor is left and if that is the recording actor * If it would stop, delayed audio might not start. */ if (this.areActorsFinished() && !this.loops && !this.wasRecording) { this.stopPlayback(false); return false; } return true; } /** * The same thing as play, but don't play the actor that is passed * in the arguments (because he might be recorded by the player) */ public void startPlayback(int tick) { if (this.getWorld().isRemote || this.playing || this.replays.isEmpty()) { return; } for (Replay replay : this.replays) { if (replay.id.isEmpty()) { RecordUtils.broadcastError("director.empty_filename"); return; } } this.collectActors(null); EntityLivingBase firstActor = null; for (Map.Entry<Replay, RecordPlayer> entry : this.actors.entrySet()) { Replay replay = entry.getKey(); RecordPlayer actor = entry.getValue(); if (firstActor == null) { firstActor = actor.actor; } actor.startPlaying(replay.id, tick, !this.loops); } this.playing = true; this.sendCommand(this.startCommand); if (firstActor != null) { CommonProxy.damage.addDamageControl(this, firstActor); } this.audioHandler.startAudio(tick); this.wasRecording = false; this.paused = false; this.tick = tick; } /** * The same thing as play, but don't play the replay that is passed * in the arguments (because he might be recorded by the player) * * Used by recording code. */ public void startPlayback(String exception, int tick) { if (this.getWorld().isRemote || this.playing) { return; } this.collectActors(this.getByFile(exception)); for (Map.Entry<Replay, RecordPlayer> entry : this.actors.entrySet()) { Replay replay = entry.getKey(); RecordPlayer actor = entry.getValue(); actor.startPlaying(replay.id, tick, true); } this.playing = true; this.sendCommand(this.startCommand); this.audioHandler.startAudio(tick); this.wasRecording = true; this.paused = false; this.tick = tick; } /** * Spawns actors at given tick in idle mode and pause the scene. This is pretty useful * for positioning cameras for exact positions. */ public boolean spawn(int tick) { if (this.replays.isEmpty()) { return false; } if (!this.actors.isEmpty()) { this.stopPlayback(true); } for (Replay replay : this.replays) { if (replay.id.isEmpty()) { RecordUtils.broadcastError("director.empty_filename"); return false; } } this.collectActors(null); this.playing = true; this.paused = true; int j = 0; for (Map.Entry<Replay, RecordPlayer> entry : this.actors.entrySet()) { Replay replay = entry.getKey(); RecordPlayer actor = entry.getValue(); if (j == 0 && actor.actor != null) { CommonProxy.damage.addDamageControl(this, actor.actor); } actor.playing = false; actor.startPlaying(replay.id, tick, true); actor.sync = true; actor.pause(); for (int i = 0; i <= tick; i++) { actor.record.applyAction(i - actor.record.preDelay, actor.actor); } actor.record.applyPreviousMorph(actor.actor, replay, tick, Record.MorphType.PAUSE); j++; } this.audioHandler.pauseAudio(tick); this.tick = tick; return true; } /** * Force stop playback * * @param triggered - true if it was caused by something, and false if it just ended playing */ public void stopPlayback(boolean triggered) { if (!triggered && !this.wasRecording || triggered) { this.wasRecording = false; } if (this.getWorld().isRemote || !this.playing) { return; } this.tick = 0; for (Map.Entry<Replay, RecordPlayer> entry : this.actors.entrySet()) { RecordPlayer actor = entry.getValue(); actor.kill = true; actor.stopPlaying(); } CommonProxy.damage.restoreDamageControl(this, this.getWorld()); this.targetPlayers.forEach((playerState) -> { playerState.resetPlayerState(); }); this.targetPlayers.clear(); this.audioHandler.stopAudio(); this.actors.clear(); this.playing = false; this.sendCommand(this.stopCommand); } /** * Toggle scene's playback */ public boolean togglePlayback() { if (this.playing) { this.stopPlayback(true); } else { this.startPlayback(0); } return this.playing; } /** * Collect actors. * * This method is responsible for collecting actors the ones that in the * world and also the ones that doesn't exist (they will be created and * spawned later on). */ private void collectActors(Replay exception) { this.actors.clear(); this.actorsCount = 0; for (Replay replay : this.replays) { if (replay == exception || !replay.enabled) { continue; } World world = this.getWorld(); EntityLivingBase actor = null; boolean real = false; /* Locate the target player */ if (!replay.target.isEmpty()) { EntityPlayerMP player = this.getTargetPlayer(replay.target); if (player != null) { if (!this.isPlayerTargetPlayback(player)) { this.targetPlayers.add(new PlayerState(player)); } actor = player; real = true; } } if (actor == null && replay.fake) { GameProfile profile = new GameProfile(new UUID(0, this.actorsCount), replay.name.isEmpty() ? "Player" : replay.name); if (replay.morph instanceof PlayerMorph) { profile = ((PlayerMorph) replay.morph).profile; } EntityPlayerMP player = new EntityPlayerMP(world.getMinecraftServer(), (WorldServer) world, profile, new PlayerInteractionManager(world)); NetworkManager manager = new NetworkManager(EnumPacketDirection.SERVERBOUND); try { manager.channelActive(new FakeContext()); } catch (Exception e) { e.printStackTrace(); } IRecording recording = Recording.get(player); recording.setFakePlayer(true); /* There is no way to construct a CPacketClientSettings on the * server side without using this hack, because the other constructor * is available only on the client side... */ PacketBuffer buffer = new PacketBuffer(Unpooled.buffer(64)); buffer.writeString("en_US"); buffer.writeByte((byte) 10); buffer.writeEnumValue(EntityPlayer.EnumChatVisibility.FULL); buffer.writeBoolean(true); buffer.writeByte(127); buffer.writeEnumValue(EnumHandSide.RIGHT); CPacketClientSettings packet = new CPacketClientSettings(); try { packet.readPacketData(buffer); } catch (IOException e) { e.printStackTrace(); } /* Skins layers don't show up by default, for some * reason, thus I have to manually set it myself */ player.handleClientSettings(packet); player.connection = new NetHandlerPlayServer(world.getMinecraftServer(), manager, player); actor = player; } else if (actor == null) { EntityActor entity = new EntityActor(this.getWorld()); entity.wasAttached = true; actor = entity; } RecordPlayer player = CommonProxy.manager.play(replay.id, actor, Mode.BOTH, 0, true); if (real) { player.realPlayer(); } if (player != null) { player.setReplay(replay); this.actorsCount++; replay.apply(actor); this.actors.put(replay, player); } } if (Blockbuster.modelBlockResetOnPlayback.get()) { lastUpdate = System.currentTimeMillis(); } } /** * Get target player */ private EntityPlayerMP getTargetPlayer(String target) { PlayerList list = this.world.getMinecraftServer().getPlayerList(); if (target.equals("@r")) { /* Pick a random player */ return list.getPlayers().get((int) (list.getPlayers().size() * Math.random())); } else if (target.startsWith("@")) { /* Pick the first player from given team */ Team team = this.world.getScoreboard().getTeam(target.substring(1)); if (team != null && !team.getMembershipCollection().isEmpty()) { return list.getPlayerByUsername(team.getMembershipCollection().iterator().next()); } } /* Get the player by username */ return list.getPlayerByUsername(target); } public boolean isPlaying() { for (RecordPlayer player : this.actors.values()) { if (player.playing) { return true; } } return false; } /** * Pause the director block playback (basically, pause all actors) */ public void pause() { for (RecordPlayer actor : this.actors.values()) { actor.pause(); } this.audioHandler.pauseAudio(); this.paused = true; } /** * Resume paused director block playback (basically, resume all actors) * @param tick the tick at which to resume playing. If -1 the scene will just play at the tick it was paused at. */ public void resume(int tick) { if (tick >= 0) { this.tick = tick; } for (RecordPlayer player : this.actors.values()) { player.resume(tick); } this.audioHandler.resume(this.tick); this.paused = false; } /** * Make actors go to the given tick */ public void goTo(int tick, boolean actions) { this.tick = tick; for (Map.Entry<Replay, RecordPlayer> entry : this.actors.entrySet()) { Replay replay = entry.getKey(); if (tick == 0) { replay.apply(entry.getValue().actor); } entry.getValue().goTo(tick, actions); } this.audioHandler.goTo(tick); } /** * Reload actors */ public void reload(int tick) { this.stopPlayback(true); this.spawn(tick); } /** * Duplicate */ public boolean dupe(int index) { if (index < 0 || index >= this.replays.size()) { return false; } Replay replay = this.replays.get(index).copy(); replay.id = this.getNextSuffix(replay.id); this.replays.add(replay); return true; } /** * Return next base suffix, this fixes issue with getNextSuffix() when the * scene's name is "tia_6", and it returns "tia_1" instead of "tia_6_1" */ public String getNextBaseSuffix(String filename) { if (filename.isEmpty()) { return filename; } return this.getNextSuffix(filename + "_0"); } public String getNextSuffix(String filename) { if (filename.isEmpty()) { return filename; } Matcher matcher = NUMBERED_SUFFIX.matcher(filename); String prefix = filename; boolean found = matcher.find(); int max = 0; if (found) { prefix = filename.substring(0, matcher.start()); } for (Replay other : this.replays) { if (other.id.startsWith(prefix)) { matcher = NUMBERED_SUFFIX.matcher(other.id); if (matcher.find() && other.id.substring(0, matcher.start()).equals(prefix)) { max = Math.max(max, Integer.parseInt(matcher.group(1))); } } } return prefix + "_" + (max + 1); } public void setupIds() { for (Replay replay : this.replays) { if (replay.id.isEmpty()) { replay.id = this.getNextBaseSuffix(this.getId()); } } } public void renamePrefix(String newPrefix) { this.renamePrefix(null, newPrefix, null); } public void renamePrefix(@Nullable String oldPrefix, String newPrefix, Function<String, String> process) { //default format <scene name>_<id> for (Replay replay : this.replays) { Matcher matcher = PREFIX.matcher(replay.id); /* test whether <scene name> is at the beginning * and whether there are multiple indexes*/ if (oldPrefix != null && replay.id.startsWith(oldPrefix+"_")) { String indexes = replay.id.substring(oldPrefix.length()+1); //length+1 to exclude "_" Matcher matcherIndexes = INDEXES.matcher(indexes); int counter = 0; while (matcherIndexes.find()) { counter++; } /* there are mutliple indexes seperated by _ */ if (counter > 1) { replay.id = newPrefix + "_" + indexes; continue; } } if (matcher.find()) { replay.id = newPrefix + "_" + matcher.group(2); } else if (process != null) { replay.id = process.apply(replay.id); } } } /** * Send a command */ public void sendCommand(String command) { if (this.sender != null && !command.isEmpty()) { this.getWorld().getMinecraftServer().commandManager.executeCommand(this.sender, command); } } /** * Log first actor's ticks (for debug purposes) */ public void logTicks() { if (this.actors.isEmpty()) { return; } RecordPlayer actor = this.actors.values().iterator().next(); if (actor != null) { Blockbuster.LOGGER.info("Director tick: " + actor.getTick()); } } /** * Sends the audio state to the player. * @param player */ public void syncAudio(EntityPlayerMP player) { this.audioHandler.syncPlayer(player); } public void copy(Scene scene) { /* There is no need to copy itself, copying itself will lead to * lost of replay data as it clears its replays and then will have * nothing to copy over... */ if (this == scene) { return; } this.replays.clear(); scene.replays.forEach((element) -> { this.replays.add(element.copy()); }); this.loops = scene.loops; this.title = scene.title; this.startCommand = scene.startCommand; this.stopCommand = scene.stopCommand; this.audioHandler.copy(scene.audioHandler); } /* NBT methods */ public void fromNBT(NBTTagCompound compound) { this.replays.clear(); NBTTagList tagList = compound.getTagList("Actors", 10); for (int i = 0; i < tagList.tagCount(); i++) { Replay replay = new Replay(); replay.fromNBT(tagList.getCompoundTagAt(i)); this.replays.add(replay); } this.loops = compound.getBoolean("Loops"); this.title = compound.getString("Title"); this.startCommand = compound.getString("StartCommand"); this.stopCommand = compound.getString("StopCommand"); this.audioHandler.fromNBT(compound); } public void toNBT(NBTTagCompound compound) { NBTTagList tagList = new NBTTagList(); for (int i = 0; i < this.replays.size(); i++) { NBTTagCompound tag = new NBTTagCompound(); this.replays.get(i).toNBT(tag); tagList.appendTag(tag); } compound.setTag("Actors", tagList); compound.setBoolean("Loops", this.loops); compound.setString("Title", this.title); compound.setString("StartCommand", this.startCommand); compound.setString("StopCommand", this.stopCommand); this.audioHandler.toNBT(compound); } /* ByteBuf methods */ public void fromBuf(ByteBuf buffer) { this.id = ByteBufUtils.readUTF8String(buffer); this.replays.clear(); for (int i = 0, c = buffer.readInt(); i < c; i++) { Replay replay = new Replay(); this.replays.add(replay); replay.fromBuf(buffer); } this.loops = buffer.readBoolean(); this.title = ByteBufUtils.readUTF8String(buffer); this.startCommand = ByteBufUtils.readUTF8String(buffer); this.stopCommand = ByteBufUtils.readUTF8String(buffer); this.audioHandler.fromBytes(buffer); } public void toBuf(ByteBuf buffer) { ByteBufUtils.writeUTF8String(buffer, this.id); buffer.writeInt(this.replays.size()); for (Replay replay : this.replays) { replay.toBuf(buffer); } buffer.writeBoolean(this.loops); ByteBufUtils.writeUTF8String(buffer, this.title); ByteBufUtils.writeUTF8String(buffer, this.startCommand); ByteBufUtils.writeUTF8String(buffer, this.stopCommand); this.audioHandler.toBytes(buffer); } /** * Class that stores an {@link EntityPlayer} and it's states like inventory etc. * This is used for scene first person playback, to reset those players to their * original state at the end of playback. */ public class PlayerState { private EntityPlayer player; private NonNullList<ItemStack> mainInventory; private int experienceLevel; /** * The total amount of experience the player has. This also includes the amount of experience within their * Experience Bar. */ private int experienceTotal; /** The current amount of experience the player has within their Experience Bar. */ private float experience; private int foodLevel; public PlayerState(EntityPlayer player) { this.player = player; /* data structure used for mainInventory List in InventoryPlayer class */ this.mainInventory = NonNullList.<ItemStack>withSize(36, ItemStack.EMPTY); for (int i = 0; i < this.mainInventory.size(); i++) { this.mainInventory.set(i, player.inventory.mainInventory.get(i).copy()); } this.experience = player.experience; this.experienceLevel = player.experienceLevel; this.experienceTotal = player.experienceTotal; this.foodLevel = player.getFoodStats().getFoodLevel(); } public EntityPlayer getPlayer() { return this.player; } /** * Resets the player's attributes stored by this state */ public void resetPlayerState() { for (int i = 0; i < this.player.inventory.mainInventory.size(); i++) { this.player.inventory.mainInventory.set(i, this.mainInventory.get(i).copy()); } this.player.experience = this.experience; this.player.experienceLevel = this.experienceLevel; this.player.experienceTotal = this.experienceTotal; this.player.getFoodStats().setFoodLevel(this.foodLevel); } } }
30,885
Java
.java
mchorse/blockbuster
159
39
10
2016-06-17T21:52:40Z
2024-05-08T20:37:12Z