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
DocxTemplate.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/util/DocxTemplate.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Function; import java.util.regex.MatchResult; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; import lombok.AllArgsConstructor; import lombok.Data; import lombok.SneakyThrows; import lombok.val; public class DocxTemplate<T> { private XWPFDocument document; private final File templateFile; private T dataSource; private final TextTemplate<T> textFormatter; private final Function<T, byte[]> imageGenerator; // The id attribute of wp:docPr tags has to be unique, but can be arbitrarily large private int uniqueID = 1000; // To differentiate our own unique id's from original we check their length as originals should be shorter than 4 digits. private final int uniqueIDDigits = (int) Math.log10(uniqueID); // Precompile regex patterns used for filling the template private final Pattern docxImageReplacer = Pattern.compile("<a:blip r:embed=\"rId\\d\">"); private final Pattern docxTextReplacer = Pattern.compile("(<w:t(?: .*)?>.*)#(\\w)(.*</w:t>)"); // Regex templates for fixing errors in the resulting document private final Pattern docPrUniqueIdFix = Pattern.compile(String.format("<wp:docPr id=\"\\d{1,%d}\"", uniqueIDDigits)); public DocxTemplate(File templateFile, TextTemplate<T> textFormatter, Function<T, byte[]> imageGenerator) { this.templateFile = templateFile; this.textFormatter = textFormatter; this.imageGenerator = imageGenerator; } public XWPFDocument generate(T dataSource) throws IOException, XmlException { try (val templateStream = new FileInputStream(templateFile)) { document = new XWPFDocument(templateStream); } this.dataSource = dataSource; val imageIds = addImagesToDocMedia(); val templateBuffer = getTemplateBuffer(); // The section properties is at the end of body and sets headers, footers, etc. val sectionProperties = (CTSectPr) document.getDocument().getBody().getSectPr().copy(); // Remove template page from final doc document.getDocument().setBody(new XWPFDocument().getDocument().getBody()); // Generate new Pages PageData<T> pageDataSource = ZipPageData(dataSource, imageIds); val templateXml = getParagraphTemplateXml(templateBuffer); List<XmlObject> paragraphs = applyPageParagraphXml(templateXml, pageDataSource); for (int paragraphIndex = 0; paragraphIndex < templateXml.size(); paragraphIndex++) { val paragraph = document.createParagraph(); paragraph.getCTP().set(paragraphs.get(paragraphIndex)); } // Reapply the section properties document.getDocument().getBody().setSectPr(sectionProperties); return document; } private List<String> addImagesToDocMedia() { val doc = document; val indexDataSource = new ArrayList<Indexed<T>>(1); for (int i = 0; i < 1; i++) { indexDataSource.add(new Indexed<>(i, dataSource)); } val indexedList = indexDataSource .parallelStream() .unordered() .map(indexData -> new Indexed<>(indexData.index, imageGenerator.apply(indexData.value))) .map(image -> { synchronized (doc) { try { return new Indexed<>(image.index, document.addPictureData(image.value, Document.PICTURE_TYPE_PNG)); } catch (InvalidFormatException e) { throw new RuntimeException(e); } } }) .collect(Collectors.toList()); return indexedList .stream() .sorted(Comparator.comparingInt(indexed -> indexed.index)) .map(Indexed::getValue) .collect(Collectors.toList()); } private byte[] getTemplateBuffer() throws IOException { try (val bufferStream = new ByteArrayOutputStream()) { document.write(bufferStream); return bufferStream.toByteArray(); } } @SneakyThrows private List<XmlObject> applyPageParagraphXml(List<String> templateXml, PageData<T> data) { val replacedParagraphs = new ArrayList<XmlObject>(templateXml.size()); for (val template : templateXml) { val paragraphXml = applyTemplateToXml(data, template); replacedParagraphs.add(XmlObject.Factory.parse(paragraphXml)); } return replacedParagraphs; } private List<String> getParagraphTemplateXml(byte[] templateBuffer) throws IOException { try (val templateStream = new ByteArrayInputStream(templateBuffer); val template = new XWPFDocument(templateStream)) { return template.getParagraphs() .stream() .map(xwpfParagraph -> xwpfParagraph.getCTP().xmlText()) .collect(Collectors.toList()); } } private String applyTemplateToXml(PageData<T> pageData, String templateXml) { val data = pageData.data; val imgIndex = pageData.qrCodeId; // Replace text markers templateXml = complexReplaceAll(templateXml, docxTextReplacer, match -> { // Group 2 contains the placeholder without the # val placeholder = match.group(2); val replacement = textFormatter.apply(data, placeholder); // Save text and XML tags around the template placeholder (group 1 & 3) return match.group(1) + replacement + match.group(3); }); // Replace qr code image templateXml = complexReplaceAll(templateXml, docxImageReplacer, matchResult -> String.format("<a:blip r:embed=\"%s\">", imgIndex)); templateXml = complexReplaceAll(templateXml, docPrUniqueIdFix, matchResult -> String.format("<wp:docPr id=\"%d\"", uniqueID++)); return templateXml; } private String complexReplaceAll(String template, Pattern pattern, Function<MatchResult, String> replacement) { while (true) { val matcher = pattern.matcher(template); if (!matcher.find()) { break; } template = matcher.replaceFirst(replacement.apply(matcher.toMatchResult())); } return template; } private PageData<T> ZipPageData(T data, Iterable<String> qrImageIds) { return new PageData(data, qrImageIds.iterator().next()); } public interface TextTemplate<T> { String apply(T data, String templatePlaceholder); } @Data @AllArgsConstructor private class PageData<D> { private D data; private String qrCodeId; } @Data @AllArgsConstructor private static class Indexed<T> { private int index; private T value; } }
8,310
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
AttributeEncryptor.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/util/AttributeEncryptor.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.util; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.spec.SecretKeySpec; import javax.persistence.AttributeConverter; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Encryptor class which encrypts and decrypts column values tagged with @Convert using the AES algorithm provided by JDK. */ @Component public class AttributeEncryptor implements AttributeConverter<String, String> { private final String AES = "AES"; private final Key key; private final Cipher cipher; public AttributeEncryptor(@Value("${db.encryption.secret:corona-ctt-20201}") String secret) throws Exception { byte[] hashedSecret = MessageDigest.getInstance("SHA-256").digest(secret.getBytes()); key = new SecretKeySpec(hashedSecret, AES); cipher = Cipher.getInstance(AES); } @Override public String convertToDatabaseColumn(String attribute) { try { synchronized (cipher) { cipher.init(Cipher.ENCRYPT_MODE, key); return Base64.getEncoder().encodeToString(cipher.doFinal(attribute.getBytes())); } } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) { throw new IllegalStateException(e); } } @Override public String convertToEntityAttribute(String dbData) { try { synchronized (cipher) { cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(Base64.getDecoder().decode(dbData))); } } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) { throw new IllegalStateException(e); } } }
2,771
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
Event.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/Event.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Entity @Getter @Setter @ToString @NoArgsConstructor public class Event { @Id @GeneratedValue private Long id; private String name; @ManyToOne(cascade = CascadeType.ALL) private Room room; private Date datum; private String createdBy; public Event(String name, Room room, Date datum, String createdBy) { this.name = name; this.room = room; this.datum = datum; this.createdBy = createdBy; } public int getRoomCapacity() { return room.getMaxCapacity(); } }
1,662
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
Visitor.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/Visitor.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import de.hs_mannheim.informatik.ct.util.AttributeEncryptor; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Table(indexes = @Index(columnList = "email")) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Visitor { @Id @GeneratedValue private Long id; @Column(unique = true, nullable = false) @NonNull @Convert(converter = AttributeEncryptor.class) private String email; public Visitor(String email) { this.email = email; } @Override public String toString() { return "{email='" + email + "'}"; } public String getName() { return ""; } public String getAddress() { return ""; } public String getNumber() { return ""; } }
2,034
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ExternalVisitor.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/ExternalVisitor.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import de.hs_mannheim.informatik.ct.util.AttributeEncryptor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; @Entity @NoArgsConstructor @Getter @Setter public class ExternalVisitor extends Visitor { @Column @NonNull @Convert(converter = AttributeEncryptor.class) private String name; @Column @Convert(converter = AttributeEncryptor.class) private String number; @Column @Convert(converter = AttributeEncryptor.class) private String address; public static ExternalVisitor visitorWithPhone(String email, String name, String number) { return new ExternalVisitor(email, name, number, null); } public static ExternalVisitor visitorWithAddress(String email, String name, String address) { return new ExternalVisitor(email, name, null, address); } public ExternalVisitor(String email, String name, String number, String address) { super(email); this.name = name; this.number = number; this.address = address; } @Override public String getName() { return this.name; } @Override public String getAddress() { return this.address; } @Override public String getNumber() { return this.number; } }
2,230
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
StudyRoom.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/StudyRoom.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class StudyRoom { String roomName; String buildingName; int maxCapacity; long visitorCount; }
1,010
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
Visit.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/Visit.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import java.util.Date; public interface Visit { Visitor getVisitor(); Date getStartDate(); Date getEndDate(); String getLocationName(); }
968
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisit.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/RoomVisit.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.var; @Entity @Getter @AllArgsConstructor @NoArgsConstructor public class RoomVisit implements Visit { @ManyToOne @JoinColumn @NonNull private Room room; @Id @GeneratedValue private Long id; @Column(updatable = false) private Date startDate; @Column private Date endDate = null; @ManyToOne @JoinColumn @NonNull private Visitor visitor; @Column @Enumerated private CheckOutSource checkOutSource = CheckOutSource.NotCheckedOut; public RoomVisit(@NonNull Visitor visitor, @NonNull Room room, Date startDate) { this.visitor = visitor; this.room = room; this.startDate = startDate; } @Override public String getLocationName() { return room.getName(); } public void checkOut(@NonNull Date checkOutDate, @NonNull CheckOutSource reason) { // normal check out // or enddate was set but user did not got checked out if (endDate == null && reason != CheckOutSource.NotCheckedOut) { endDate = checkOutDate; checkOutSource = reason; } else if (checkOutSource == CheckOutSource.NotCheckedOut) { checkOutSource = CheckOutSource.AutomaticCheckout; } } public CheckOutSource getCheckOutSource() { assert endDate != null || checkOutSource == CheckOutSource.NotCheckedOut; return checkOutSource; } @lombok.Data @NoArgsConstructor public static class Data { @NonNull private String roomId; @NonNull private String roomName; private int roomCapacity; private int currentVisitorCount; private String visitorEmail; private Date startDate = null; private Date endDate = null; private String name; private String address; private String number; private String roomPin; private boolean privileged; public Data(RoomVisit visit, int currentVisitorCount) { if (visit.visitor instanceof ExternalVisitor) { var externalVisitor = (ExternalVisitor) visit.visitor; this.address = externalVisitor.getAddress(); this.name = externalVisitor.getName(); this.number = externalVisitor.getNumber(); } this.roomId = visit.room.getId(); this.roomName = visit.room.getName(); this.roomCapacity = visit.room.getMaxCapacity(); this.visitorEmail = visit.visitor.getEmail(); this.currentVisitorCount = currentVisitorCount; this.startDate = visit.startDate; this.endDate = visit.endDate; } public Data(Room.Data roomData) { this.roomId = roomData.getRoomId(); this.roomName = roomData.getRoomName(); this.roomCapacity = roomData.getMaxCapacity(); } } }
4,130
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventVisit.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/EventVisit.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.MapsId; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; @Entity @Getter @NoArgsConstructor public class EventVisit implements Visit { @EmbeddedId @Getter(value = AccessLevel.NONE) private PrimaryKey id; @Column(updatable = false) private Date startDate; @Column private Date endDate; @ManyToOne @MapsId("eventId") @NonNull private Event event; @ManyToOne @MapsId("visitorId") @NonNull private Visitor visitor; public EventVisit(Event event, Visitor visitor, Date startDate) { this.event = event; this.visitor = visitor; this.startDate = startDate; this.id = new PrimaryKey(event, visitor); } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String getLocationName() { return event.getName(); } @Embeddable @Data @NoArgsConstructor public static class PrimaryKey implements Serializable { PrimaryKey(Event event, Visitor visitor) { this.eventId = event.getId(); this.visitorId = visitor.getId(); } @NonNull @Column(nullable = false) private Long eventId; @NonNull @Column(nullable = false) private Long visitorId; } }
2,451
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
Room.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/Room.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import java.util.Random; import javax.persistence.Entity; import javax.persistence.Id; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; @Entity @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class Room { @Id @NonNull private String name; private String buildingName; private int maxCapacity; private String roomPin; public Room(String name, String buildingName, int maxCapacity) { this.name = name; this.buildingName = buildingName; this.maxCapacity = maxCapacity; this.roomPin = String.format("%04d", new Random().nextInt(10000)); } public String getId() { return getName(); } @lombok.Data @NoArgsConstructor public static class Data { @NonNull private String roomName; @NonNull private String roomId; private int maxCapacity; @NonNull private String building; @NonNull private String roomPin; public Data(Room room) { roomName = room.getName(); roomId = room.getId(); maxCapacity = room.getMaxCapacity(); building = room.getBuildingName(); roomPin = room.getRoomPin(); } } }
2,140
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
CheckOutSource.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/CheckOutSource.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; public enum CheckOutSource { NotCheckedOut, UserCheckout, AutomaticCheckout, RoomReset; public static CheckOutSource getDefault() { return CheckOutSource.UserCheckout; } }
1,005
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
Contact.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/model/Contact.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Contact<T extends Visit> { private T targetVisit; private T contactVisit; /** * * @return the infected person */ public Visitor getTarget() { return targetVisit.getVisitor(); } /** * * @return likely contact of infected person */ public Visitor getContact() { return contactVisit.getVisitor(); } public String getContactLocation() { assert targetVisit.getLocationName().equals(contactVisit.getLocationName()); return targetVisit.getLocationName(); } }
1,471
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VarIntTest.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/test/java/cn/nukkit/test/VarIntTest.java
package cn.nukkit.test; import cn.nukkit.utils.BinaryStream; import cn.nukkit.utils.VarInt; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; /** * By lmlstarqaq http://snake1999.com/ * Creation time: 2017/7/5 23:22. */ @DisplayName("VarInt") class VarIntTest { @DisplayName("ZigZag") @Test void testZigZag() { assertAll( () -> assertEquals(0x2468acf0, VarInt.encodeZigZag32(0x12345678)), () -> assertEquals(0x2b826b1d, VarInt.encodeZigZag32(0xea3eca71)), () -> assertEquals(0x12345678, VarInt.decodeZigZag32(0x2468acf0)), () -> assertEquals(0xea3eca71, VarInt.decodeZigZag32(0x2b826b1d)), () -> assertEquals(2623536930346282224L, VarInt.encodeZigZag64(0x1234567812345678L)), () -> assertEquals(3135186066796324391L, VarInt.encodeZigZag64(0xea3eca710becececL)), () -> assertEquals(0x1234567812345678L, VarInt.decodeZigZag64(2623536930346282224L)), () -> assertEquals(0xea3eca710becececL, VarInt.decodeZigZag64(3135186066796324391L)) ); } @DisplayName("Writing") @Test void testWrite() throws IOException { BinaryStream bs = new BinaryStream(); VarInt.writeUnsignedVarInt(bs, 237356812); VarInt.writeVarInt(bs, 0xea3eca71); VarInt.writeUnsignedVarLong(bs, 0x1234567812345678L); VarInt.writeVarLong(bs, 0xea3eca710becececL); assertAll( () -> assertEquals(237356812, VarInt.readUnsignedVarInt(bs)), () -> assertEquals(0xea3eca71, VarInt.readVarInt(bs)), () -> assertEquals(0x1234567812345678L, VarInt.readUnsignedVarLong(bs)), () -> assertEquals(0xea3eca710becececL, VarInt.readVarLong(bs)) ); ByteArrayOutputStream os = new ByteArrayOutputStream(); VarInt.writeUnsignedVarInt(os, 237356812); VarInt.writeVarInt(os, 0xea3eca71); VarInt.writeUnsignedVarLong(os, 0x1234567812345678L); VarInt.writeVarLong(os, 0xea3eca710becececL); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); assertAll( () -> assertEquals(237356812, VarInt.readUnsignedVarInt(is)), () -> assertEquals(0xea3eca71, VarInt.readVarInt(is)), () -> assertEquals(0x1234567812345678L, VarInt.readUnsignedVarLong(is)), () -> assertEquals(0xea3eca710becececL, VarInt.readVarLong(is)) ); } @DisplayName("Reading") @Test void testRead() { assertAll( () -> assertEquals(2412, VarInt.readUnsignedVarInt(wrapBinaryStream("EC123EC456"))), () -> assertEquals(583868, VarInt.readUnsignedVarInt(wrapBinaryStream("BCD123EFA0"))), () -> assertEquals(1206, VarInt.readVarInt(wrapBinaryStream("EC123EC456"))), () -> assertEquals(291934, VarInt.readVarInt(wrapBinaryStream("BCD123EFA0"))), () -> assertEquals(6015, VarInt.readUnsignedVarLong(wrapBinaryStream("FF2EC456EC789EC012EC"))), () -> assertEquals(3694, VarInt.readUnsignedVarLong(wrapBinaryStream("EE1CD34BCD56BCD78BCD"))), () -> assertEquals(-3008, VarInt.readVarLong(wrapBinaryStream("FF2EC456EC789EC012EC"))), () -> assertEquals(1847, VarInt.readVarLong(wrapBinaryStream("EE1CD34BCD56BCD78BCD"))) ); } private static BinaryStream wrapBinaryStream(String hex) { return new BinaryStream(hexStringToByte(hex)); } private static byte[] hexStringToByte(String hex) { int len = (hex.length() / 2); byte[] result = new byte[len]; char[] aChar = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (toByte(aChar[pos]) << 4 | toByte(aChar[pos + 1])); } return result; } private static byte toByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } }
3,742
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
AngleTest.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/test/java/cn/nukkit/test/AngleTest.java
package cn.nukkit.test; import cn.nukkit.math.Angle; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static cn.nukkit.math.Angle.*; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Copyright 2017 lmlstarqaq * All rights reserved. */ @DisplayName("Angle") class AngleTest { @DisplayName("Angle operations") @Test void testAngle() { Angle rd1 = fromRadian(1.0); Angle rf1 = fromRadian(1.0f); Angle dd1 = fromDegree(180.0); Angle df1 = fromDegree(180.0f); assertEquals("57.29578\t57.29577951308232\t1.0\t1.0", rd1.asFloatDegree() + "\t" + rd1.asDoubleDegree() + "\t" + rd1.asFloatRadian() + "\t" + rd1.asDoubleRadian()); assertEquals("57.295776\t57.29577951308232\t1.0\t1.0", rf1.asFloatDegree() + "\t" + rf1.asDoubleDegree() + "\t" + rf1.asFloatRadian() + "\t" + rf1.asDoubleRadian()); assertEquals("180.0\t180.0\t3.1415927\t3.141592653589793", dd1.asFloatDegree() + "\t" + dd1.asDoubleDegree() + "\t" + dd1.asFloatRadian() + "\t" + dd1.asDoubleRadian()); assertEquals("180.0\t180.0\t3.1415927\t3.141592653589793", df1.asFloatDegree() + "\t" + df1.asDoubleDegree() + "\t" + df1.asFloatRadian() + "\t" + df1.asDoubleRadian()); assertEquals("Angle[Double, 1.000000rad = 57.295780deg] [1072693248]", rd1.toString()); assertEquals("Angle[Float, 1.000000rad = 57.295776deg] [1065353216]", rf1.toString()); assertEquals("Angle[Double, 180.000000deg = 3.141593rad] [-341077452]", dd1.toString()); assertEquals("Angle[Float, 180.000000deg = 3.141593rad] [-386330060]", df1.toString()); Angle rd2 = fromRadian(200.0); Angle rf2 = fromRadian(200.0f); Angle dd2 = fromDegree(23333.33); Angle df2 = fromDegree(23333.33f); assertEquals("11459.156\t11459.155902616465\t200.0\t200.0", rd2.asFloatDegree() + "\t" + rd2.asDoubleDegree() + "\t" + rd2.asFloatRadian() + "\t" + rd2.asDoubleRadian()); assertEquals("11459.155\t11459.155902616465\t200.0\t200.0", rf2.asFloatDegree() + "\t" + rf2.asDoubleDegree() + "\t" + rf2.asFloatRadian() + "\t" + rf2.asDoubleRadian()); assertEquals("23333.33\t23333.33\t407.24344\t407.24343395436847", dd2.asFloatDegree() + "\t" + dd2.asDoubleDegree() + "\t" + dd2.asFloatRadian() + "\t" + dd2.asDoubleRadian()); assertEquals("23333.33\t23333.330078125\t407.24344\t407.243435317907", df2.asFloatDegree() + "\t" + df2.asDoubleDegree() + "\t" + df2.asFloatRadian() + "\t" + df2.asDoubleRadian()); assertEquals("0.8414709848078965\t0.5403023058681398\t1.5574077246549023", rd1.sin() + "\t" + rd1.cos() + "\t" +rd1.tan()); assertEquals("1.2246467991473532E-16\t-1.0\t-1.2246467991473532E-16", dd1.sin() + "\t" + dd1.cos() + "\t" +dd1.tan()); Angle asin1 = asin(1); Angle asin2 = asin(1.0/2.0); Angle acos1 = acos(1); Angle acos2 = acos(1.0/2.0); Angle atan1 = atan(1); Angle atan2 = atan(1.0/2.0); assertEquals("Angle[Double, 1.570796rad = 90.000000deg] [1807551715]\tAngle[Double, 0.000000rad = 0.000000deg] [0]\tAngle[Double, 0.785398rad = 45.000000deg] [1806503139]", asin1.toString() + "\t" + acos1.toString() + "\t" + atan1.toString()); assertEquals("Angle[Double, 0.523599rad = 30.000000deg] [130921012]\tAngle[Double, 1.047198rad = 60.000000deg] [131969588]\tAngle[Double, 0.463648rad = 26.565051deg] [985405224]", asin2.toString() + "\t" + acos2.toString() + "\t" + atan2.toString()); assertEquals(1, compare(asin(2.0/3.0), asin(1.0/2.0))); assertEquals("Angle[Double, 22.000000rad = 1260.507149deg] [1077280768]\tAngle[Float, 22.000000rad = 1260.507080deg] [1102053376]", fromRadian(22.0d).toString() + "\t" + fromRadian(22.0f).toString()); assertEquals("Angle[Double, 1.000000rad = 57.295780deg] [1072693248]\tAngle[Double, 57.295780deg = 1.000000rad] [-236816880]", fromRadian(1.0d).toString() + "\t" + fromDegree(57.29577951308232d).toString()); assertEquals("Angle[Double, 1.000000rad = 57.295780deg] [1072693248]\tAngle[Double, 1.000000deg = 0.017453rad] [-1807936972]", fromRadian(1.0d).toString() + "\t" + fromDegree(1.0d).toString()); } }
4,030
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ClientChainDataTest.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/test/java/cn/nukkit/test/ClientChainDataTest.java
package cn.nukkit.test; import cn.nukkit.utils.ClientChainData; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.InputStream; import static org.junit.jupiter.api.Assertions.assertEquals; /** * An example to show how to use ClientChainData * This is also a test for client chain data. * * By lmlstarqaq http://snake1999.com/ * Creation time: 2017/6/7 15:07. */ @DisplayName("ClientChainData") class ClientChainDataTest { @DisplayName("Getters") @Test void testGetter() throws Exception { InputStream is = ClientChainDataTest.class.getResourceAsStream("chain.dat"); ClientChainData data = ClientChainData.of(readStream(is)); String got = String.format("userName=%s, clientUUID=%s, " + "identityPublicKey=%s, clientId=%d, " + "serverAddress=%s, deviceModel=%s, " + "deviceOS=%d, gameVersion=%s, " + "guiScale=%d, languageCode=%s, " + "xuid=%s, currentInputMode=%d, " + "defaultInputMode=%d, UIProfile=%d" , data.getUsername(), data.getClientUUID(), data.getIdentityPublicKey(), data.getClientId(), data.getServerAddress(), data.getDeviceModel(), data.getDeviceOS(), data.getGameVersion(), data.getGuiScale(), data.getLanguageCode(), data.getXUID(), data.getCurrentInputMode(), data.getDefaultInputMode(), data.getUIProfile() ); String expecting = "userName=lmlstarqaq, clientUUID=8323afe1-641e-3b61-9a92-d5d20b279065, " + "identityPublicKey=MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE4lyvA1iVhV2u3pLQqJAjJnJZSlSjib8mM1uB5h5yqOBSvCHW+nZxDmkOAW6MS1GA7yGHitGmfS4jW/yUISUdWvLzEWJYOzphb3GNh5J1oLJRwESc5278i4MEDk1y21/q, " + "clientId=-6315607246631494544, " + "serverAddress=192.168.1.108:19132, deviceModel=iPhone6,2, " + "deviceOS=2, gameVersion=1.1.0, " + "guiScale=0, languageCode=zh_CN, " + "xuid=2535465134455915, currentInputMode=2, " + "defaultInputMode=2, UIProfile=1"; assertEquals(got, expecting); } private static byte[] readStream(InputStream inStream) throws Exception { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[65536]; int len; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } }
2,346
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ZlibTest.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/test/java/cn/nukkit/test/ZlibTest.java
package cn.nukkit.test; import cn.nukkit.utils.Zlib; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertTrue; @DisplayName("Zlib") class ZlibTest { @DisplayName("Inflate and Deflate") @Test void testAll() throws Exception { byte[] in = "lmlstarqaq".getBytes(); byte[] compressed = Zlib.deflate(in); byte[] out = Zlib.inflate(compressed); assertTrue(Arrays.equals(in, out)); } }
536
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Nukkit.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/Nukkit.java
package cn.nukkit; import cn.nukkit.command.CommandReader; import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.utils.LogLevel; import cn.nukkit.utils.MainLogger; import cn.nukkit.utils.ServerKiller; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; /** * `_ _ _ _ _ _ * | \ | | | | | | (_) | * | \| |_ _| | _| | ___| |_ * | . ` | | | | |/ / |/ / | __| * | |\ | |_| | <| <| | |_ * |_| \_|\__,_|_|\_\_|\_\_|\__| */ /** * Nukkit启动类,包含{@code main}函数。<br> * The launcher class of Nukkit, including the {@code main} function. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public class Nukkit { public final static String VERSION = "1.0dev"; public final static String API_VERSION = "1.0.5"; public final static String CODENAME = "蘋果(Apple)派(Pie)"; @Deprecated public final static String MINECRAFT_VERSION = ProtocolInfo.MINECRAFT_VERSION; @Deprecated public final static String MINECRAFT_VERSION_NETWORK = ProtocolInfo.MINECRAFT_VERSION_NETWORK; public final static String PATH = System.getProperty("user.dir") + "/"; public final static String DATA_PATH = System.getProperty("user.dir") + "/"; public final static String PLUGIN_PATH = DATA_PATH + "plugins"; public static final long START_TIME = System.currentTimeMillis(); public static boolean ANSI = true; public static boolean shortTitle = false; public static int DEBUG = 1; public static void main(String[] args) { // prefer IPv4 to stop any weird RakNet issues. System.setProperty("java.net.preferIPv4Stack", "true"); //Shorter title for windows 8/2012 String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("windows")) { if (osName.contains("windows 8") || osName.contains("2012")) { shortTitle = true; } } LogLevel logLevel = LogLevel.DEFAULT_LEVEL; int index = -1; boolean skip = false; //启动参数 for (String arg : args) { index++; if (skip) { skip = false; continue; } switch (arg) { case "disable-ansi": ANSI = false; break; case "--verbosity": case "-v": skip = true; try { String levelName = args[index + 1]; Set<String> levelNames = Arrays.stream(LogLevel.values()).map(level -> level.name().toLowerCase()).collect(Collectors.toSet()); if (!levelNames.contains(levelName.toLowerCase())) { System.out.printf("'%s' is not a valid log level, using the default\n", levelName); continue; } logLevel = Arrays.stream(LogLevel.values()).filter(level -> level.name().equalsIgnoreCase(levelName)).findAny().orElse(LogLevel.DEFAULT_LEVEL); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("You must enter the requested log level, using the default\n"); } } } MainLogger logger = new MainLogger(DATA_PATH + "server.log", logLevel); System.out.printf("Using log level '%s'\n", logLevel); try { if (ANSI) { System.out.print((char) 0x1b + "]0;Starting Nukkit Server For Minecraft: PE" + (char) 0x07); } new Server(logger, PATH, DATA_PATH, PLUGIN_PATH); } catch (Exception e) { logger.logException(e); } if (ANSI) { System.out.print((char) 0x1b + "]0;Stopping Server..." + (char) 0x07); } logger.info("Stopping other threads"); for (Thread thread : java.lang.Thread.getAllStackTraces().keySet()) { if (!(thread instanceof InterruptibleThread)) { continue; } logger.debug("Stopping " + thread.getClass().getSimpleName() + " thread"); if (thread.isAlive()) { thread.interrupt(); } } ServerKiller killer = new ServerKiller(8); killer.start(); logger.shutdown(); logger.interrupt(); CommandReader.getInstance().removePromptLine(); if (ANSI) { System.out.print((char) 0x1b + "]0;Server Stopped" + (char) 0x07); } System.exit(0); } }
4,736
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Server.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/Server.java
package cn.nukkit; import cn.nukkit.block.Block; import cn.nukkit.blockentity.*; import cn.nukkit.command.*; import cn.nukkit.entity.Attribute; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.data.Skin; import cn.nukkit.entity.item.*; import cn.nukkit.entity.mob.*; import cn.nukkit.entity.passive.*; import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.entity.projectile.EntityEgg; import cn.nukkit.entity.projectile.EntityEnderPearl; import cn.nukkit.entity.projectile.EntitySnowball; import cn.nukkit.event.HandlerList; import cn.nukkit.event.level.LevelInitEvent; import cn.nukkit.event.level.LevelLoadEvent; import cn.nukkit.event.server.QueryRegenerateEvent; import cn.nukkit.inventory.CraftingManager; import cn.nukkit.inventory.Recipe; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.lang.BaseLang; import cn.nukkit.lang.TextContainer; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.level.Level; import cn.nukkit.level.Position; import cn.nukkit.level.format.LevelProvider; import cn.nukkit.level.format.LevelProviderManager; import cn.nukkit.level.format.anvil.Anvil; import cn.nukkit.level.format.leveldb.LevelDB; import cn.nukkit.level.format.mcregion.McRegion; import cn.nukkit.level.generator.Flat; import cn.nukkit.level.generator.Generator; import cn.nukkit.level.generator.Nether; import cn.nukkit.level.generator.Normal; import cn.nukkit.level.generator.biome.Biome; import cn.nukkit.math.NukkitMath; import cn.nukkit.metadata.EntityMetadataStore; import cn.nukkit.metadata.LevelMetadataStore; import cn.nukkit.metadata.PlayerMetadataStore; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.network.CompressBatchedTask; import cn.nukkit.network.Network; import cn.nukkit.network.RakNetInterface; import cn.nukkit.network.SourceInterface; import cn.nukkit.network.protocol.BatchPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.network.protocol.PlayerListPacket; import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.network.query.QueryHandler; import cn.nukkit.network.rcon.RCON; import cn.nukkit.permission.BanEntry; import cn.nukkit.permission.BanList; import cn.nukkit.permission.DefaultPermissions; import cn.nukkit.permission.Permissible; import cn.nukkit.plugin.JavaPluginLoader; import cn.nukkit.plugin.Plugin; import cn.nukkit.plugin.PluginLoadOrder; import cn.nukkit.plugin.PluginManager; import cn.nukkit.plugin.service.NKServiceManager; import cn.nukkit.plugin.service.ServiceManager; import cn.nukkit.potion.Effect; import cn.nukkit.potion.Potion; import cn.nukkit.resourcepacks.ResourcePackManager; import cn.nukkit.scheduler.FileWriteTask; import cn.nukkit.scheduler.ServerScheduler; import cn.nukkit.utils.*; import cn.nukkit.utils.bugreport.ExceptionHandler; import co.aikar.timings.Timings; import com.google.common.base.Preconditions; import java.io.*; import java.nio.ByteOrder; import java.util.*; /** * @author MagicDroidX * @author Box */ public class Server { public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "nukkit.broadcast.admin"; public static final String BROADCAST_CHANNEL_USERS = "nukkit.broadcast.user"; private static Server instance = null; private BanList banByName = null; private BanList banByIP = null; private Config operators = null; private Config whitelist = null; private boolean isRunning = true; private boolean hasStopped = false; private PluginManager pluginManager = null; private int profilingTickrate = 20; private ServerScheduler scheduler = null; private int tickCounter; private long nextTick; private final float[] tickAverage = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}; private final float[] useAverage = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; private float maxTick = 20; private float maxUse = 0; private int sendUsageTicker = 0; private boolean dispatchSignals = false; private final MainLogger logger; private final CommandReader console; private SimpleCommandMap commandMap; private CraftingManager craftingManager; private ResourcePackManager resourcePackManager; private ConsoleCommandSender consoleSender; private int maxPlayers; private boolean autoSave; private RCON rcon; private EntityMetadataStore entityMetadata; private PlayerMetadataStore playerMetadata; private LevelMetadataStore levelMetadata; private Network network; private boolean networkCompressionAsync = true; public int networkCompressionLevel = 7; private int networkZlibProvider = 0; private boolean autoTickRate = true; private int autoTickRateLimit = 20; private boolean alwaysTickPlayers = false; private int baseTickRate = 1; private Boolean getAllowFlight = null; private int difficulty = Integer.MAX_VALUE; private int defaultGamemode = Integer.MAX_VALUE; private int autoSaveTicker = 0; private int autoSaveTicks = 6000; private BaseLang baseLang; private boolean forceLanguage = false; private UUID serverID; private final String filePath; private final String dataPath; private final String pluginPath; private final Set<UUID> uniquePlayers = new HashSet<>(); private QueryHandler queryHandler; private QueryRegenerateEvent queryRegenerateEvent; private Config properties; private Config config; private final Map<String, Player> players = new HashMap<>(); private final Map<UUID, Player> playerList = new HashMap<>(); private final Map<Integer, String> identifier = new HashMap<>(); private final Map<Integer, Level> levels = new HashMap<Integer, Level>() { public Level put(Integer key, Level value) { Level result = super.put(key, value); levelArray = levels.values().toArray(new Level[levels.size()]); return result; } public boolean remove(Object key, Object value) { boolean result = super.remove(key, value); levelArray = levels.values().toArray(new Level[levels.size()]); return result; } public Level remove(Object key) { Level result = super.remove(key); levelArray = levels.values().toArray(new Level[levels.size()]); return result; } }; private Level[] levelArray = new Level[0]; private final ServiceManager serviceManager = new NKServiceManager(); private Level defaultLevel = null; private Thread currentThread; private Watchdog watchdog; Server(MainLogger logger, final String filePath, String dataPath, String pluginPath) { Preconditions.checkState(instance == null, "Already initialized!"); currentThread = Thread.currentThread(); // Saves the current thread instance as a reference, used in Server#isPrimaryThread() instance = this; this.logger = logger; this.filePath = filePath; if (!new File(dataPath + "worlds/").exists()) { new File(dataPath + "worlds/").mkdirs(); } if (!new File(dataPath + "players/").exists()) { new File(dataPath + "players/").mkdirs(); } if (!new File(pluginPath).exists()) { new File(pluginPath).mkdirs(); } this.dataPath = new File(dataPath).getAbsolutePath() + "/"; this.pluginPath = new File(pluginPath).getAbsolutePath() + "/"; this.console = new CommandReader(); //todo: VersionString 现在不必要 if (!new File(this.dataPath + "nukkit.yml").exists()) { this.getLogger().info(TextFormat.GREEN + "Welcome! Please choose a language first!"); try { String[] lines = Utils.readFile(this.getClass().getClassLoader().getResourceAsStream("lang/language.list")).split("\n"); for (String line : lines) { this.getLogger().info(line); } } catch (IOException e) { throw new RuntimeException(e); } String fallback = BaseLang.FALLBACK_LANGUAGE; String language = null; while (language == null) { String lang = this.console.readLine(); InputStream conf = this.getClass().getClassLoader().getResourceAsStream("lang/" + lang + "/lang.ini"); if (conf != null) { language = lang; } } InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/" + language + "/nukkit.yml"); if (advacedConf == null) { advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/" + fallback + "/nukkit.yml"); } try { Utils.writeFile(this.dataPath + "nukkit.yml", advacedConf); } catch (IOException e) { throw new RuntimeException(e); } } this.console.start(); this.logger.info("Loading " + TextFormat.GREEN + "nukkit.yml" + TextFormat.WHITE + "..."); this.config = new Config(this.dataPath + "nukkit.yml", Config.YAML); this.logger.info("Loading " + TextFormat.GREEN + "server properties" + TextFormat.WHITE + "..."); this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ConfigSection() { { put("motd", "Nukkit Server For Minecraft: PE"); put("sub-motd", "Powered by Nukkit"); put("server-port", 19132); put("server-ip", "0.0.0.0"); put("view-distance", 10); put("white-list", false); put("achievements", true); put("announce-player-achievements", true); put("spawn-protection", 16); put("max-players", 20); put("allow-flight", false); put("spawn-animals", true); put("spawn-mobs", true); put("gamemode", 0); put("force-gamemode", false); put("hardcore", false); put("pvp", true); put("difficulty", 1); put("generator-settings", ""); put("level-name", "world"); put("level-seed", ""); put("level-type", "DEFAULT"); put("enable-query", true); put("enable-rcon", false); put("rcon.password", Base64.getEncoder().encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13)); put("auto-save", true); put("force-resources", false); put("bug-report", true); put("xbox-auth", true); } }); this.forceLanguage = (Boolean) this.getConfig("settings.force-language", false); this.baseLang = new BaseLang((String) this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE)); this.logger.info(this.getLanguage().translateString("language.selected", new String[]{getLanguage().getName(), getLanguage().getLang()})); this.logger.info(getLanguage().translateString("nukkit.server.start", TextFormat.AQUA + this.getVersion() + TextFormat.WHITE)); Object poolSize = this.getConfig("settings.async-workers", "auto"); if (!(poolSize instanceof Integer)) { try { poolSize = Integer.valueOf((String) poolSize); } catch (Exception e) { poolSize = Math.max(Runtime.getRuntime().availableProcessors() + 1, 4); } } ServerScheduler.WORKERS = (int) poolSize; this.networkZlibProvider = (int) this.getConfig("network.zlib-provider", 2); Zlib.setProvider(this.networkZlibProvider); this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7); this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true); this.autoTickRate = (boolean) this.getConfig("level-settings.auto-tick-rate", true); this.autoTickRateLimit = (int) this.getConfig("level-settings.auto-tick-rate-limit", 20); this.alwaysTickPlayers = (boolean) this.getConfig("level-settings.always-tick-players", false); this.baseTickRate = (int) this.getConfig("level-settings.base-tick-rate", 1); this.scheduler = new ServerScheduler(); if (this.getPropertyBoolean("enable-rcon", false)) { this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().equals("")) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort())); } this.entityMetadata = new EntityMetadataStore(); this.playerMetadata = new PlayerMetadataStore(); this.levelMetadata = new LevelMetadataStore(); this.operators = new Config(this.dataPath + "ops.txt", Config.ENUM); this.whitelist = new Config(this.dataPath + "white-list.txt", Config.ENUM); this.banByName = new BanList(this.dataPath + "banned-players.json"); this.banByName.load(); this.banByIP = new BanList(this.dataPath + "banned-ips.json"); this.banByIP.load(); this.maxPlayers = this.getPropertyInt("max-players", 20); this.setAutoSave(this.getPropertyBoolean("auto-save", true)); if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) { this.setPropertyInt("difficulty", 3); } Nukkit.DEBUG = (int) this.getConfig("debug.level", 1); if (this.logger instanceof MainLogger) { this.logger.setLogDebug(Nukkit.DEBUG > 1); } if (this.getConfig().getBoolean("bug-report", true)) { ExceptionHandler.registerExceptionHandler(); } this.logger.info(this.getLanguage().translateString("nukkit.server.networkStart", new String[]{this.getIp().equals("") ? "*" : this.getIp(), String.valueOf(this.getPort())})); this.serverID = UUID.randomUUID(); this.network = new Network(this); this.network.setName(this.getMotd()); this.network.setSubName(this.getSubMotd()); this.logger.info(this.getLanguage().translateString("nukkit.server.info", this.getName(), TextFormat.YELLOW + this.getNukkitVersion() + TextFormat.WHITE, TextFormat.AQUA + this.getCodename() + TextFormat.WHITE, this.getApiVersion())); this.logger.info(this.getLanguage().translateString("nukkit.server.license", this.getName())); this.consoleSender = new ConsoleCommandSender(); this.commandMap = new SimpleCommandMap(this); this.registerEntities(); this.registerBlockEntities(); Block.init(); Enchantment.init(); Item.init(); Biome.init(); Effect.init(); Potion.init(); Attribute.init(); this.craftingManager = new CraftingManager(); this.resourcePackManager = new ResourcePackManager(new File(Nukkit.DATA_PATH, "resource_packs")); this.pluginManager = new PluginManager(this, this.commandMap); this.pluginManager.subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this.consoleSender); this.pluginManager.registerInterface(JavaPluginLoader.class); this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5); this.network.registerInterface(new RakNetInterface(this)); this.pluginManager.loadPlugins(this.pluginPath); this.enablePlugins(PluginLoadOrder.STARTUP); LevelProviderManager.addProvider(this, Anvil.class); LevelProviderManager.addProvider(this, McRegion.class); LevelProviderManager.addProvider(this, LevelDB.class); Generator.addGenerator(Flat.class, "flat", Generator.TYPE_FLAT); Generator.addGenerator(Normal.class, "normal", Generator.TYPE_INFINITE); Generator.addGenerator(Normal.class, "default", Generator.TYPE_INFINITE); Generator.addGenerator(Nether.class, "nether", Generator.TYPE_NETHER); //todo: add old generator and hell generator for (String name : ((Map<String, Object>) this.getConfig("worlds", new HashMap<>())).keySet()) { if (!this.loadLevel(name)) { long seed; try { seed = ((Integer) this.getConfig("worlds." + name + ".seed")).longValue(); } catch (Exception e) { seed = System.currentTimeMillis(); } Map<String, Object> options = new HashMap<>(); String[] opts = ((String) this.getConfig("worlds." + name + ".generator", Generator.getGenerator("default").getSimpleName())).split(":"); Class<? extends Generator> generator = Generator.getGenerator(opts[0]); if (opts.length > 1) { String preset = ""; for (int i = 1; i < opts.length; i++) { preset += opts[i] + ":"; } preset = preset.substring(0, preset.length() - 1); options.put("preset", preset); } this.generateLevel(name, seed, generator, options); } } if (this.getDefaultLevel() == null) { String defaultName = this.getPropertyString("level-name", "world"); if (defaultName == null || defaultName.trim().isEmpty()) { this.getLogger().warning("level-name cannot be null, using default"); defaultName = "world"; this.setPropertyString("level-name", defaultName); } if (!this.loadLevel(defaultName)) { long seed; String seedString = String.valueOf(this.getProperty("level-seed", System.currentTimeMillis())); try { seed = Long.valueOf(seedString); } catch (NumberFormatException e) { seed = seedString.hashCode(); } this.generateLevel(defaultName, seed == 0 ? System.currentTimeMillis() : seed); } this.setDefaultLevel(this.getLevelByName(defaultName)); } this.properties.save(true); if (this.getDefaultLevel() == null) { this.getLogger().emergency(this.getLanguage().translateString("nukkit.level.defaultError")); this.forceShutdown(); return; } if ((int) this.getConfig("ticks-per.autosave", 6000) > 0) { this.autoSaveTicks = (int) this.getConfig("ticks-per.autosave", 6000); } this.enablePlugins(PluginLoadOrder.POSTWORLD); this.watchdog = new Watchdog(this, 60000); this.watchdog.start(); this.start(); } public int broadcastMessage(String message) { return this.broadcast(message, BROADCAST_CHANNEL_USERS); } public int broadcastMessage(TextContainer message) { return this.broadcast(message, BROADCAST_CHANNEL_USERS); } public int broadcastMessage(String message, CommandSender[] recipients) { for (CommandSender recipient : recipients) { recipient.sendMessage(message); } return recipients.length; } public int broadcastMessage(String message, Collection<CommandSender> recipients) { for (CommandSender recipient : recipients) { recipient.sendMessage(message); } return recipients.size(); } public int broadcastMessage(TextContainer message, Collection<CommandSender> recipients) { for (CommandSender recipient : recipients) { recipient.sendMessage(message); } return recipients.size(); } public int broadcast(String message, String permissions) { Set<CommandSender> recipients = new HashSet<>(); for (String permission : permissions.split(";")) { for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) { if (permissible instanceof CommandSender && permissible.hasPermission(permission)) { recipients.add((CommandSender) permissible); } } } for (CommandSender recipient : recipients) { recipient.sendMessage(message); } return recipients.size(); } public int broadcast(TextContainer message, String permissions) { Set<CommandSender> recipients = new HashSet<>(); for (String permission : permissions.split(";")) { for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) { if (permissible instanceof CommandSender && permissible.hasPermission(permission)) { recipients.add((CommandSender) permissible); } } } for (CommandSender recipient : recipients) { recipient.sendMessage(message); } return recipients.size(); } public static void broadcastPacket(Collection<Player> players, DataPacket packet) { broadcastPacket(players.stream().toArray(Player[]::new), packet); } public static void broadcastPacket(Player[] players, DataPacket packet) { packet.encode(); packet.isEncoded = true; if (packet.pid() == ProtocolInfo.BATCH_PACKET) { for (Player player : players) { player.dataPacket(packet); } } else { getInstance().batchPackets(players, new DataPacket[]{packet}, true); } if (packet.encapsulatedPacket != null) { packet.encapsulatedPacket = null; } } public void batchPackets(Player[] players, DataPacket[] packets) { this.batchPackets(players, packets, false); } public void batchPackets(Player[] players, DataPacket[] packets, boolean forceSync) { if (players == null || packets == null || players.length == 0 || packets.length == 0) { return; } Timings.playerNetworkSendTimer.startTiming(); byte[][] payload = new byte[packets.length * 2][]; int size = 0; for (int i = 0; i < packets.length; i++) { DataPacket p = packets[i]; if (!p.isEncoded) { p.encode(); } byte[] buf = p.getBuffer(); payload[i * 2] = Binary.writeUnsignedVarInt(buf.length); payload[i * 2 + 1] = buf; packets[i] = null; size += payload[i * 2].length; size += payload[i * 2 + 1].length; } List<String> targets = new ArrayList<>(); for (Player p : players) { if (p.isConnected()) { targets.add(this.identifier.get(p.rawHashCode())); } } if (!forceSync && this.networkCompressionAsync) { this.getScheduler().scheduleAsyncTask(new CompressBatchedTask(payload, targets, this.networkCompressionLevel)); } else { try { byte[] data = Binary.appendBytes(payload); this.broadcastPacketsCallback(Zlib.deflate(data, this.networkCompressionLevel), targets); } catch (Exception e) { throw new RuntimeException(e); } } Timings.playerNetworkSendTimer.stopTiming(); } public void broadcastPacketsCallback(byte[] data, List<String> identifiers) { BatchPacket pk = new BatchPacket(); pk.payload = data; for (String i : identifiers) { if (this.players.containsKey(i)) { this.players.get(i).dataPacket(pk); } } } public void enablePlugins(PluginLoadOrder type) { for (Plugin plugin : new ArrayList<>(this.pluginManager.getPlugins().values())) { if (!plugin.isEnabled() && type == plugin.getDescription().getOrder()) { this.enablePlugin(plugin); } } if (type == PluginLoadOrder.POSTWORLD) { this.commandMap.registerServerAliases(); DefaultPermissions.registerCorePermissions(); } } public void enablePlugin(Plugin plugin) { this.pluginManager.enablePlugin(plugin); } public void disablePlugins() { this.pluginManager.disablePlugins(); } public boolean dispatchCommand(CommandSender sender, String commandLine) throws ServerException { // First we need to check if this command is on the main thread or not, if not, warn the user if (!this.isPrimaryThread()) { getLogger().warning("Command Dispatched Async: " + commandLine); getLogger().warning("Please notify author of plugin causing this execution to fix this bug!", new Throwable()); // TODO: We should sync the command to the main thread too! } if (sender == null) { throw new ServerException("CommandSender is not valid"); } if (this.commandMap.dispatch(sender, commandLine)) { return true; } sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.unknown", commandLine)); return false; } //todo: use ticker to check console public ConsoleCommandSender getConsoleSender() { return consoleSender; } public void reload() { this.logger.info("Reloading..."); this.logger.info("Saving levels..."); for (Level level : this.levelArray) { level.save(); } this.pluginManager.disablePlugins(); this.pluginManager.clearPlugins(); this.commandMap.clearCommands(); this.logger.info("Reloading properties..."); this.properties.reload(); this.maxPlayers = this.getPropertyInt("max-players", 20); if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) { this.setPropertyInt("difficulty", difficulty = 3); } this.banByIP.load(); this.banByName.load(); this.reloadWhitelist(); this.operators.reload(); for (BanEntry entry : this.getIPBans().getEntires().values()) { this.getNetwork().blockAddress(entry.getName(), -1); } this.pluginManager.registerInterface(JavaPluginLoader.class); this.pluginManager.loadPlugins(this.pluginPath); this.enablePlugins(PluginLoadOrder.STARTUP); this.enablePlugins(PluginLoadOrder.POSTWORLD); Timings.reset(); } public void shutdown() { if (this.watchdog != null) { this.watchdog.kill(); } if (this.isRunning) { ServerKiller killer = new ServerKiller(90); killer.start(); } this.isRunning = false; } public void forceShutdown() { if (this.hasStopped) { return; } try { if (!this.isRunning) { //todo sendUsage } // clean shutdown of console thread asap this.console.shutdown(); this.hasStopped = true; this.shutdown(); if (this.rcon != null) { this.rcon.close(); } this.getLogger().debug("Disabling all plugins"); this.pluginManager.disablePlugins(); for (Player player : new ArrayList<>(this.players.values())) { player.close(player.getLeaveMessage(), (String) this.getConfig("settings.shutdown-message", "Server closed")); } this.getLogger().debug("Unloading all levels"); for (Level level : this.levelArray) { this.unloadLevel(level, true); } this.getLogger().debug("Removing event handlers"); HandlerList.unregisterAll(); this.getLogger().debug("Stopping all tasks"); this.scheduler.cancelAllTasks(); this.scheduler.mainThreadHeartbeat(Integer.MAX_VALUE); this.getLogger().debug("Closing console"); this.console.interrupt(); this.getLogger().debug("Stopping network interfaces"); for (SourceInterface interfaz : this.network.getInterfaces()) { interfaz.shutdown(); this.network.unregisterInterface(interfaz); } this.getLogger().debug("Disabling timings"); Timings.stopServer(); //todo other things } catch (Exception e) { this.logger.logException(e); //todo remove this? this.logger.emergency("Exception happened while shutting down, exit the process"); System.exit(1); } } public void start() { if (this.getPropertyBoolean("enable-query", true)) { this.queryHandler = new QueryHandler(); } for (BanEntry entry : this.getIPBans().getEntires().values()) { this.network.blockAddress(entry.getName(), -1); } //todo send usage setting this.tickCounter = 0; this.logger.info(this.getLanguage().translateString("nukkit.server.defaultGameMode", getGamemodeString(this.getGamemode()))); this.logger.info(this.getLanguage().translateString("nukkit.server.startFinished", String.valueOf((double) (System.currentTimeMillis() - Nukkit.START_TIME) / 1000))); this.tickProcessor(); this.forceShutdown(); } public void handlePacket(String address, int port, byte[] payload) { try { if (payload.length > 2 && Arrays.equals(Binary.subBytes(payload, 0, 2), new byte[]{(byte) 0xfe, (byte) 0xfd}) && this.queryHandler != null) { this.queryHandler.handle(address, port, payload); } } catch (Exception e) { this.logger.logException(e); this.getNetwork().blockAddress(address, 600); } } private int lastLevelGC; public void tickProcessor() { this.nextTick = System.currentTimeMillis(); try { while (this.isRunning) { try { this.tick(); long next = this.nextTick; long current = System.currentTimeMillis(); if (next - 0.1 > current) { long allocated = next - current - 1; { // Instead of wasting time, do something potentially useful int offset = 0; for (int i = 0; i < levelArray.length; i++) { offset = (i + lastLevelGC) % levelArray.length; Level level = levelArray[offset]; level.doGarbageCollection(allocated - 1); allocated = next - System.currentTimeMillis(); if (allocated <= 0) { break; } } lastLevelGC = offset + 1; } if (allocated > 0) { Thread.sleep(allocated, 900000); } } } catch (RuntimeException e) { this.getLogger().logException(e); } } } catch (Throwable e) { this.logger.emergency("Exception happened while ticking server"); this.logger.alert(Utils.getExceptionMessage(e)); this.logger.alert(Utils.getAllThreadDumps()); } } public void onPlayerCompleteLoginSequence(Player player) { this.sendFullPlayerListData(player); } public void onPlayerLogin(Player player) { if (this.sendUsageTicker > 0) { this.uniquePlayers.add(player.getUniqueId()); } } public void addPlayer(String identifier, Player player) { this.players.put(identifier, player); this.identifier.put(player.rawHashCode(), identifier); } public void addOnlinePlayer(Player player) { this.playerList.put(player.getUniqueId(), player); this.updatePlayerListData(player.getUniqueId(), player.getId(), player.getDisplayName(), player.getSkin(), player.getLoginChainData().getXUID()); } public void removeOnlinePlayer(Player player) { if (this.playerList.containsKey(player.getUniqueId())) { this.playerList.remove(player.getUniqueId()); PlayerListPacket pk = new PlayerListPacket(); pk.type = PlayerListPacket.TYPE_REMOVE; pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(player.getUniqueId())}; Server.broadcastPacket(this.playerList.values(), pk); } } public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin) { this.updatePlayerListData(uuid, entityId, name, skin, "", this.playerList.values()); } public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId) { this.updatePlayerListData(uuid, entityId, name, skin, xboxUserId, this.playerList.values()); } public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, Player[] players) { this.updatePlayerListData(uuid, entityId, name, skin, "", players); } public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId, Player[] players) { PlayerListPacket pk = new PlayerListPacket(); pk.type = PlayerListPacket.TYPE_ADD; pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(uuid, entityId, name, skin, xboxUserId)}; Server.broadcastPacket(players, pk); } public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId, Collection<Player> players) { this.updatePlayerListData(uuid, entityId, name, skin, xboxUserId, players.stream() .filter(p -> !p.getUniqueId().equals(uuid)) .toArray(Player[]::new)); } public void removePlayerListData(UUID uuid) { this.removePlayerListData(uuid, this.playerList.values()); } public void removePlayerListData(UUID uuid, Player[] players) { PlayerListPacket pk = new PlayerListPacket(); pk.type = PlayerListPacket.TYPE_REMOVE; pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(uuid)}; Server.broadcastPacket(players, pk); } public void removePlayerListData(UUID uuid, Collection<Player> players) { this.removePlayerListData(uuid, players.stream().toArray(Player[]::new)); } public void sendFullPlayerListData(Player player) { PlayerListPacket pk = new PlayerListPacket(); pk.type = PlayerListPacket.TYPE_ADD; pk.entries = this.playerList.values().stream() .map(p -> new PlayerListPacket.Entry( p.getUniqueId(), p.getId(), p.getDisplayName(), p.getSkin(), p.getLoginChainData().getXUID())) .toArray(PlayerListPacket.Entry[]::new); player.dataPacket(pk); } public void sendRecipeList(Player player) { player.dataPacket(CraftingManager.packet); } private void checkTickUpdates(int currentTick, long tickTime) { for (Player p : new ArrayList<>(this.players.values())) { /*if (!p.loggedIn && (tickTime - p.creationTime) >= 10000 && p.kick(PlayerKickEvent.Reason.LOGIN_TIMEOUT, "Login timeout")) { continue; } client freezes when applying resource packs todo: fix*/ if (this.alwaysTickPlayers) { p.onUpdate(currentTick); } } //Do level ticks for (Level level : this.levelArray) { if (level.getTickRate() > this.baseTickRate && --level.tickRateCounter > 0) { continue; } try { long levelTime = System.currentTimeMillis(); level.doTick(currentTick); int tickMs = (int) (System.currentTimeMillis() - levelTime); level.tickRateTime = tickMs; if (this.autoTickRate) { if (tickMs < 50 && level.getTickRate() > this.baseTickRate) { int r; level.setTickRate(r = level.getTickRate() - 1); if (r > this.baseTickRate) { level.tickRateCounter = level.getTickRate(); } this.getLogger().debug("Raising level \"" + level.getName() + "\" tick rate to " + level.getTickRate() + " ticks"); } else if (tickMs >= 50) { if (level.getTickRate() == this.baseTickRate) { level.setTickRate((int) Math.max(this.baseTickRate + 1, Math.min(this.autoTickRateLimit, Math.floor(tickMs / 50)))); this.getLogger().debug("Level \"" + level.getName() + "\" took " + NukkitMath.round(tickMs, 2) + "ms, setting tick rate to " + level.getTickRate() + " ticks"); } else if ((tickMs / level.getTickRate()) >= 50 && level.getTickRate() < this.autoTickRateLimit) { level.setTickRate(level.getTickRate() + 1); this.getLogger().debug("Level \"" + level.getName() + "\" took " + NukkitMath.round(tickMs, 2) + "ms, setting tick rate to " + level.getTickRate() + " ticks"); } level.tickRateCounter = level.getTickRate(); } } } catch (Exception e) { if (Nukkit.DEBUG > 1 && this.logger != null) { this.logger.logException(e); } this.logger.critical(this.getLanguage().translateString("nukkit.level.tickError", new String[]{level.getName(), e.toString()})); this.logger.logException(e); } } } public void doAutoSave() { if (this.getAutoSave()) { Timings.levelSaveTimer.startTiming(); for (Player player : new ArrayList<>(this.players.values())) { if (player.isOnline()) { player.save(true); } else if (!player.isConnected()) { this.removePlayer(player); } } for (Level level : this.levelArray) { level.save(); } Timings.levelSaveTimer.stopTiming(); } } private boolean tick() { long tickTime = System.currentTimeMillis(); // TODO long sleepTime = tickTime - this.nextTick; if (sleepTime < -25) { try { Thread.sleep(Math.max(5, -sleepTime - 25)); } catch (InterruptedException e) { Server.getInstance().getLogger().logException(e); } } long tickTimeNano = System.nanoTime(); if ((tickTime - this.nextTick) < -25) { return false; } Timings.fullServerTickTimer.startTiming(); ++this.tickCounter; Timings.connectionTimer.startTiming(); this.network.processInterfaces(); if (this.rcon != null) { this.rcon.check(); } Timings.connectionTimer.stopTiming(); Timings.schedulerTimer.startTiming(); this.scheduler.mainThreadHeartbeat(this.tickCounter); Timings.schedulerTimer.stopTiming(); this.checkTickUpdates(this.tickCounter, tickTime); for (Player player : new ArrayList<>(this.players.values())) { player.checkNetwork(); } if ((this.tickCounter & 0b1111) == 0) { this.titleTick(); this.network.resetStatistics(); this.maxTick = 20; this.maxUse = 0; if ((this.tickCounter & 0b111111111) == 0) { try { this.getPluginManager().callEvent(this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5)); if (this.queryHandler != null) { this.queryHandler.regenerateInfo(); } } catch (Exception e) { this.logger.logException(e); } } this.getNetwork().updateName(); } if (this.autoSave && ++this.autoSaveTicker >= this.autoSaveTicks) { this.autoSaveTicker = 0; this.doAutoSave(); } if (this.sendUsageTicker > 0 && --this.sendUsageTicker == 0) { this.sendUsageTicker = 6000; //todo sendUsage } if (this.tickCounter % 100 == 0) { for (Level level : this.levelArray) { level.doChunkGarbageCollection(); } } Timings.fullServerTickTimer.stopTiming(); //long now = System.currentTimeMillis(); long nowNano = System.nanoTime(); //float tick = Math.min(20, 1000 / Math.max(1, now - tickTime)); //float use = Math.min(1, (now - tickTime) / 50); float tick = (float) Math.min(20, 1000000000 / Math.max(1000000, ((double) nowNano - tickTimeNano))); float use = (float) Math.min(1, ((double) (nowNano - tickTimeNano)) / 50000000); if (this.maxTick > tick) { this.maxTick = tick; } if (this.maxUse < use) { this.maxUse = use; } System.arraycopy(this.tickAverage, 1, this.tickAverage, 0, this.tickAverage.length - 1); this.tickAverage[this.tickAverage.length - 1] = tick; System.arraycopy(this.useAverage, 1, this.useAverage, 0, this.useAverage.length - 1); this.useAverage[this.useAverage.length - 1] = use; if ((this.nextTick - tickTime) < -1000) { this.nextTick = tickTime; } else { this.nextTick += 50; } return true; } public long getNextTick() { return nextTick; } // TODO: Fix title tick public void titleTick() { if (!Nukkit.ANSI) { return; } Runtime runtime = Runtime.getRuntime(); double used = NukkitMath.round((double) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024, 2); double max = NukkitMath.round(((double) runtime.maxMemory()) / 1024 / 1024, 2); String usage = Math.round(used / max * 100) + "%"; String title = (char) 0x1b + "]0;" + this.getName() + " " + this.getNukkitVersion() + " | Online " + this.players.size() + "/" + this.getMaxPlayers() + " | Memory " + usage; if (!Nukkit.shortTitle) { title += " | U " + NukkitMath.round((this.network.getUpload() / 1024 * 1000), 2) + " D " + NukkitMath.round((this.network.getDownload() / 1024 * 1000), 2) + " kB/s"; } title += " | TPS " + this.getTicksPerSecond() + " | Load " + this.getTickUsage() + "%" + (char) 0x07; System.out.print(title); } public QueryRegenerateEvent getQueryInformation() { return this.queryRegenerateEvent; } public String getName() { return "Nukkit"; } public boolean isRunning() { return isRunning; } public String getNukkitVersion() { return Nukkit.VERSION; } public String getCodename() { return Nukkit.CODENAME; } public String getVersion() { return ProtocolInfo.MINECRAFT_VERSION; } public String getApiVersion() { return Nukkit.API_VERSION; } public String getFilePath() { return filePath; } public String getDataPath() { return dataPath; } public String getPluginPath() { return pluginPath; } public int getMaxPlayers() { return maxPlayers; } public int getPort() { return this.getPropertyInt("server-port", 19132); } public int getViewDistance() { return this.getPropertyInt("view-distance", 10); } public String getIp() { return this.getPropertyString("server-ip", "0.0.0.0"); } public UUID getServerUniqueId() { return this.serverID; } public boolean getAutoSave() { return this.autoSave; } public void setAutoSave(boolean autoSave) { this.autoSave = autoSave; for (Level level : this.levelArray) { level.setAutoSave(this.autoSave); } } public String getLevelType() { return this.getPropertyString("level-type", "DEFAULT"); } public boolean getGenerateStructures() { return this.getPropertyBoolean("generate-structures", true); } public int getGamemode() { return this.getPropertyInt("gamemode", 0) & 0b11; } public boolean getForceGamemode() { return this.getPropertyBoolean("force-gamemode", false); } public static String getGamemodeString(int mode) { return getGamemodeString(mode, false); } public static String getGamemodeString(int mode, boolean direct) { switch (mode) { case Player.SURVIVAL: return direct ? "Survival" : "%gameMode.survival"; case Player.CREATIVE: return direct ? "Creative" : "%gameMode.creative"; case Player.ADVENTURE: return direct ? "Adventure" : "%gameMode.adventure"; case Player.SPECTATOR: return direct ? "Spectator" : "%gameMode.spectator"; } return "UNKNOWN"; } public static int getGamemodeFromString(String str) { switch (str.trim().toLowerCase()) { case "0": case "survival": case "s": return Player.SURVIVAL; case "1": case "creative": case "c": return Player.CREATIVE; case "2": case "adventure": case "a": return Player.ADVENTURE; case "3": case "spectator": case "spc": case "view": case "v": return Player.SPECTATOR; } return -1; } public static int getDifficultyFromString(String str) { switch (str.trim().toLowerCase()) { case "0": case "peaceful": case "p": return 0; case "1": case "easy": case "e": return 1; case "2": case "normal": case "n": return 2; case "3": case "hard": case "h": return 3; } return -1; } public int getDifficulty() { if (this.difficulty == Integer.MAX_VALUE) { this.difficulty = this.getPropertyInt("difficulty", 1); } return this.difficulty; } public boolean hasWhitelist() { return this.getPropertyBoolean("white-list", false); } public int getSpawnRadius() { return this.getPropertyInt("spawn-protection", 16); } public boolean getAllowFlight() { if (getAllowFlight == null) { getAllowFlight = this.getPropertyBoolean("allow-flight", false); } return getAllowFlight; } public boolean isHardcore() { return this.getPropertyBoolean("hardcore", false); } public int getDefaultGamemode() { if (this.defaultGamemode == Integer.MAX_VALUE) { this.defaultGamemode = this.getPropertyInt("gamemode", 0); } return this.defaultGamemode; } public String getMotd() { return this.getPropertyString("motd", "Nukkit Server For Minecraft: PE"); } public String getSubMotd() { return this.getPropertyString("sub-motd", "Powered by Nukkit"); } public boolean getForceResources() { return this.getPropertyBoolean("force-resources", false); } public MainLogger getLogger() { return this.logger; } public EntityMetadataStore getEntityMetadata() { return entityMetadata; } public PlayerMetadataStore getPlayerMetadata() { return playerMetadata; } public LevelMetadataStore getLevelMetadata() { return levelMetadata; } public PluginManager getPluginManager() { return this.pluginManager; } public CraftingManager getCraftingManager() { return craftingManager; } public ResourcePackManager getResourcePackManager() { return resourcePackManager; } public ServerScheduler getScheduler() { return scheduler; } public int getTick() { return tickCounter; } public float getTicksPerSecond() { return ((float) Math.round(this.maxTick * 100)) / 100; } public float getTicksPerSecondAverage() { float sum = 0; int count = this.tickAverage.length; for (float aTickAverage : this.tickAverage) { sum += aTickAverage; } return (float) NukkitMath.round(sum / count, 2); } public float getTickUsage() { return (float) NukkitMath.round(this.maxUse * 100, 2); } public float getTickUsageAverage() { float sum = 0; int count = this.useAverage.length; for (float aUseAverage : this.useAverage) { sum += aUseAverage; } return ((float) Math.round(sum / count * 100)) / 100; } public SimpleCommandMap getCommandMap() { return commandMap; } public Map<UUID, Player> getOnlinePlayers() { return new HashMap<>(playerList); } public void addRecipe(Recipe recipe) { this.craftingManager.registerRecipe(recipe); } public IPlayer getOfflinePlayer(String name) { IPlayer result = this.getPlayerExact(name.toLowerCase()); if (result == null) { return new OfflinePlayer(this, name); } return result; } public CompoundTag getOfflinePlayerData(String name) { name = name.toLowerCase(); String path = this.getDataPath() + "players/"; File file = new File(path + name + ".dat"); if (this.shouldSavePlayerData() && file.exists()) { try { return NBTIO.readCompressed(new FileInputStream(file)); } catch (Exception e) { file.renameTo(new File(path + name + ".dat.bak")); this.logger.notice(this.getLanguage().translateString("nukkit.data.playerCorrupted", name)); } } else { this.logger.notice(this.getLanguage().translateString("nukkit.data.playerNotFound", name)); } Position spawn = this.getDefaultLevel().getSafeSpawn(); CompoundTag nbt = new CompoundTag() .putLong("firstPlayed", System.currentTimeMillis() / 1000) .putLong("lastPlayed", System.currentTimeMillis() / 1000) .putList(new ListTag<DoubleTag>("Pos") .add(new DoubleTag("0", spawn.x)) .add(new DoubleTag("1", spawn.y)) .add(new DoubleTag("2", spawn.z))) .putString("Level", this.getDefaultLevel().getName()) .putList(new ListTag<>("Inventory")) .putCompound("Achievements", new CompoundTag()) .putInt("playerGameType", this.getGamemode()) .putList(new ListTag<DoubleTag>("Motion") .add(new DoubleTag("0", 0)) .add(new DoubleTag("1", 0)) .add(new DoubleTag("2", 0))) .putList(new ListTag<FloatTag>("Rotation") .add(new FloatTag("0", 0)) .add(new FloatTag("1", 0))) .putFloat("FallDistance", 0) .putShort("Fire", 0) .putShort("Air", 300) .putBoolean("OnGround", true) .putBoolean("Invulnerable", false) .putString("NameTag", name); this.saveOfflinePlayerData(name, nbt); return nbt; } public void saveOfflinePlayerData(String name, CompoundTag tag) { this.saveOfflinePlayerData(name, tag, false); } public void saveOfflinePlayerData(String name, CompoundTag tag, boolean async) { if (this.shouldSavePlayerData()) { try { if (async) { this.getScheduler().scheduleAsyncTask(new FileWriteTask(this.getDataPath() + "players/" + name.toLowerCase() + ".dat", NBTIO.writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN))); } else { Utils.writeFile(this.getDataPath() + "players/" + name.toLowerCase() + ".dat", new ByteArrayInputStream(NBTIO.writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN))); } } catch (Exception e) { this.logger.critical(this.getLanguage().translateString("nukkit.data.saveError", new String[]{name, e.getMessage()})); if (Nukkit.DEBUG > 1) { this.logger.logException(e); } } } } public Player getPlayer(String name) { Player found = null; name = name.toLowerCase(); int delta = Integer.MAX_VALUE; for (Player player : this.getOnlinePlayers().values()) { if (player.getName().toLowerCase().startsWith(name)) { int curDelta = player.getName().length() - name.length(); if (curDelta < delta) { found = player; delta = curDelta; } if (curDelta == 0) { break; } } } return found; } public Player getPlayerExact(String name) { name = name.toLowerCase(); for (Player player : this.getOnlinePlayers().values()) { if (player.getName().toLowerCase().equals(name)) { return player; } } return null; } public Player[] matchPlayer(String partialName) { partialName = partialName.toLowerCase(); List<Player> matchedPlayer = new ArrayList<>(); for (Player player : this.getOnlinePlayers().values()) { if (player.getName().toLowerCase().equals(partialName)) { return new Player[]{player}; } else if (player.getName().toLowerCase().contains(partialName)) { matchedPlayer.add(player); } } return matchedPlayer.toArray(new Player[matchedPlayer.size()]); } public void removePlayer(Player player) { if (this.identifier.containsKey(player.rawHashCode())) { String identifier = this.identifier.get(player.rawHashCode()); this.players.remove(identifier); this.identifier.remove(player.rawHashCode()); return; } for (String identifier : new ArrayList<>(this.players.keySet())) { Player p = this.players.get(identifier); if (player == p) { this.players.remove(identifier); this.identifier.remove(player.rawHashCode()); break; } } } public Map<Integer, Level> getLevels() { return levels; } public Level getDefaultLevel() { return defaultLevel; } public void setDefaultLevel(Level defaultLevel) { if (defaultLevel == null || (this.isLevelLoaded(defaultLevel.getFolderName()) && defaultLevel != this.defaultLevel)) { this.defaultLevel = defaultLevel; } } public boolean isLevelLoaded(String name) { return this.getLevelByName(name) != null; } public Level getLevel(int levelId) { if (this.levels.containsKey(levelId)) { return this.levels.get(levelId); } return null; } public Level getLevelByName(String name) { for (Level level : this.levelArray) { if (level.getFolderName().equals(name)) { return level; } } return null; } public boolean unloadLevel(Level level) { return this.unloadLevel(level, false); } public boolean unloadLevel(Level level, boolean forceUnload) { if (level == this.getDefaultLevel() && !forceUnload) { throw new IllegalStateException("The default level cannot be unloaded while running, please switch levels."); } return level.unload(forceUnload); } public boolean loadLevel(String name) { if (Objects.equals(name.trim(), "")) { throw new LevelException("Invalid empty level name"); } if (this.isLevelLoaded(name)) { return true; } else if (!this.isLevelGenerated(name)) { this.logger.notice(this.getLanguage().translateString("nukkit.level.notFound", name)); return false; } String path; if (name.contains("/") || name.contains("\\")) { path = name; } else { path = this.getDataPath() + "worlds/" + name + "/"; } Class<? extends LevelProvider> provider = LevelProviderManager.getProvider(path); if (provider == null) { this.logger.error(this.getLanguage().translateString("nukkit.level.loadError", new String[]{name, "Unknown provider"})); return false; } Level level; try { level = new Level(this, name, path, provider); } catch (Exception e) { this.logger.error(this.getLanguage().translateString("nukkit.level.loadError", new String[]{name, e.getMessage()})); this.logger.logException(e); return false; } this.levels.put(level.getId(), level); level.initLevel(); this.getPluginManager().callEvent(new LevelLoadEvent(level)); level.setTickRate(this.baseTickRate); return true; } public boolean generateLevel(String name) { return this.generateLevel(name, new java.util.Random().nextLong()); } public boolean generateLevel(String name, long seed) { return this.generateLevel(name, seed, null); } public boolean generateLevel(String name, long seed, Class<? extends Generator> generator) { return this.generateLevel(name, seed, generator, new HashMap<>()); } public boolean generateLevel(String name, long seed, Class<? extends Generator> generator, Map<String, Object> options) { return generateLevel(name, seed, generator, options, null); } public boolean generateLevel(String name, long seed, Class<? extends Generator> generator, Map<String, Object> options, Class<? extends LevelProvider> provider) { if (Objects.equals(name.trim(), "") || this.isLevelGenerated(name)) { return false; } if (!options.containsKey("preset")) { options.put("preset", this.getPropertyString("generator-settings", "")); } if (generator == null) { generator = Generator.getGenerator(this.getLevelType()); } if (provider == null) { if ((provider = LevelProviderManager.getProviderByName((String) this.getConfig("level-settings.default-format", "anvil"))) == null) { provider = LevelProviderManager.getProviderByName("anvil"); } } String path; if (name.contains("/") || name.contains("\\")) { path = name; } else { path = this.getDataPath() + "worlds/" + name + "/"; } Level level; try { provider.getMethod("generate", String.class, String.class, long.class, Class.class, Map.class).invoke(null, path, name, seed, generator, options); level = new Level(this, name, path, provider); this.levels.put(level.getId(), level); level.initLevel(); level.setTickRate(this.baseTickRate); } catch (Exception e) { this.logger.error(this.getLanguage().translateString("nukkit.level.generationError", new String[]{name, e.getMessage()})); this.logger.logException(e); return false; } this.getPluginManager().callEvent(new LevelInitEvent(level)); this.getPluginManager().callEvent(new LevelLoadEvent(level)); /*this.getLogger().notice(this.getLanguage().translateString("nukkit.level.backgroundGeneration", name)); int centerX = (int) level.getSpawnLocation().getX() >> 4; int centerZ = (int) level.getSpawnLocation().getZ() >> 4; TreeMap<String, Integer> order = new TreeMap<>(); for (int X = -3; X <= 3; ++X) { for (int Z = -3; Z <= 3; ++Z) { int distance = X * X + Z * Z; int chunkX = X + centerX; int chunkZ = Z + centerZ; order.put(Level.chunkHash(chunkX, chunkZ), distance); } } List<Map.Entry<String, Integer>> sortList = new ArrayList<>(order.entrySet()); Collections.sort(sortList, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue() - o1.getValue(); } }); for (String index : order.keySet()) { Chunk.Entry entry = Level.getChunkXZ(index); level.populateChunk(entry.chunkX, entry.chunkZ, true); }*/ return true; } public boolean isLevelGenerated(String name) { if (Objects.equals(name.trim(), "")) { return false; } String path = this.getDataPath() + "worlds/" + name + "/"; if (this.getLevelByName(name) == null) { if (LevelProviderManager.getProvider(path) == null) { return false; } } return true; } public BaseLang getLanguage() { return baseLang; } public boolean isLanguageForced() { return forceLanguage; } public Network getNetwork() { return network; } //Revising later... public Config getConfig() { return this.config; } public Object getConfig(String variable) { return this.getConfig(variable, null); } public Object getConfig(String variable, Object defaultValue) { Object value = this.config.get(variable); return value == null ? defaultValue : value; } public Config getProperties() { return this.properties; } public Object getProperty(String variable) { return this.getProperty(variable, null); } public Object getProperty(String variable, Object defaultValue) { return this.properties.exists(variable) ? this.properties.get(variable) : defaultValue; } public void setPropertyString(String variable, String value) { this.properties.set(variable, value); this.properties.save(); } public String getPropertyString(String variable) { return this.getPropertyString(variable, null); } public String getPropertyString(String variable, String defaultValue) { return this.properties.exists(variable) ? (String) this.properties.get(variable) : defaultValue; } public int getPropertyInt(String variable) { return this.getPropertyInt(variable, null); } public int getPropertyInt(String variable, Integer defaultValue) { return this.properties.exists(variable) ? (!this.properties.get(variable).equals("") ? Integer.parseInt(String.valueOf(this.properties.get(variable))) : defaultValue) : defaultValue; } public void setPropertyInt(String variable, int value) { this.properties.set(variable, value); this.properties.save(); } public boolean getPropertyBoolean(String variable) { return this.getPropertyBoolean(variable, null); } public boolean getPropertyBoolean(String variable, Object defaultValue) { Object value = this.properties.exists(variable) ? this.properties.get(variable) : defaultValue; if (value instanceof Boolean) { return (Boolean) value; } switch (String.valueOf(value)) { case "on": case "true": case "1": case "yes": return true; } return false; } public void setPropertyBoolean(String variable, boolean value) { this.properties.set(variable, value ? "1" : "0"); this.properties.save(); } public PluginIdentifiableCommand getPluginCommand(String name) { Command command = this.commandMap.getCommand(name); if (command instanceof PluginIdentifiableCommand) { return (PluginIdentifiableCommand) command; } else { return null; } } public BanList getNameBans() { return this.banByName; } public BanList getIPBans() { return this.banByIP; } public void addOp(String name) { this.operators.set(name.toLowerCase(), true); Player player = this.getPlayerExact(name); if (player != null) { player.recalculatePermissions(); } this.operators.save(true); } public void removeOp(String name) { this.operators.remove(name.toLowerCase()); Player player = this.getPlayerExact(name); if (player != null) { player.recalculatePermissions(); } this.operators.save(); } public void addWhitelist(String name) { this.whitelist.set(name.toLowerCase(), true); this.whitelist.save(true); } public void removeWhitelist(String name) { this.whitelist.remove(name.toLowerCase()); this.whitelist.save(true); } public boolean isWhitelisted(String name) { return !this.hasWhitelist() || this.operators.exists(name, true) || this.whitelist.exists(name, true); } public boolean isOp(String name) { return this.operators.exists(name, true); } public Config getWhitelist() { return whitelist; } public Config getOps() { return operators; } public void reloadWhitelist() { this.whitelist.reload(); } public ServiceManager getServiceManager() { return serviceManager; } public Map<String, List<String>> getCommandAliases() { Object section = this.getConfig("aliases"); Map<String, List<String>> result = new LinkedHashMap<>(); if (section instanceof Map) { for (Map.Entry entry : (Set<Map.Entry>) ((Map) section).entrySet()) { List<String> commands = new ArrayList<>(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof List) { for (String string : (List<String>) value) { commands.add(string); } } else { commands.add((String) value); } result.put(key, commands); } } return result; } public boolean shouldSavePlayerData() { return (Boolean) this.getConfig("player.save-player-data", true); } /** * Checks the current thread against the expected primary thread for the * server. * <p> * <b>Note:</b> this method should not be used to indicate the current * synchronized state of the runtime. A current thread matching the main * thread indicates that it is synchronized, but a mismatch does not * preclude the same assumption. * * @return true if the current thread matches the expected primary thread, * false otherwise */ public boolean isPrimaryThread() { return (Thread.currentThread() == currentThread); } public Thread getPrimaryThread() { return currentThread; } private void registerEntities() { Entity.registerEntity("Arrow", EntityArrow.class); Entity.registerEntity("Item", EntityItem.class); Entity.registerEntity("FallingSand", EntityFallingBlock.class); Entity.registerEntity("PrimedTnt", EntityPrimedTNT.class); Entity.registerEntity("Snowball", EntitySnowball.class); Entity.registerEntity("EnderPearl", EntityEnderPearl.class); Entity.registerEntity("Painting", EntityPainting.class); //Monsters Entity.registerEntity("Creeper", EntityCreeper.class); Entity.registerEntity("Blaze", EntityBlaze.class); Entity.registerEntity("CaveSpider", EntityCaveSpider.class); Entity.registerEntity("ElderGuardian", EntityElderGuardian.class); Entity.registerEntity("EnderDragon", EntityEnderDragon.class); Entity.registerEntity("Enderman", EntityEnderman.class); Entity.registerEntity("Endermite", EntityEndermite.class); Entity.registerEntity("Evoker", EntityEvoker.class); Entity.registerEntity("Ghast", EntityGhast.class); Entity.registerEntity("Guardian", EntityGuardian.class); Entity.registerEntity("Husk", EntityHusk.class); Entity.registerEntity("MagmaCube", EntityMagmaCube.class); Entity.registerEntity("Shulker", EntityShulker.class); Entity.registerEntity("Silverfish", EntitySilverfish.class); Entity.registerEntity("Skeleton", EntitySkeleton.class); Entity.registerEntity("SkeletonHorse", EntitySkeletonHorse.class); Entity.registerEntity("Slime", EntitySlime.class); Entity.registerEntity("Spider", EntitySpider.class); Entity.registerEntity("Stray", EntityStray.class); Entity.registerEntity("Vindicator", EntityVindicator.class); Entity.registerEntity("Vex", EntityVex.class); Entity.registerEntity("WitherSkeleton", EntityWitherSkeleton.class); Entity.registerEntity("Wither", EntityWither.class); Entity.registerEntity("Witch", EntityWitch.class); Entity.registerEntity("ZombiePigman", EntityZombiePigman.class); Entity.registerEntity("ZombieVillager", EntityZombieVillager.class); Entity.registerEntity("Zombie", EntityZombie.class); //Passive Entity.registerEntity("Bat", EntityBat.class); Entity.registerEntity("Chicken", EntityChicken.class); Entity.registerEntity("Cow", EntityCow.class); Entity.registerEntity("Donkey", EntityDonkey.class); Entity.registerEntity("Horse", EntityHorse.class); Entity.registerEntity("Llama", EntityLlama.class); Entity.registerEntity("Mooshroom", EntityMooshroom.class); Entity.registerEntity("Mule", EntityMule.class); Entity.registerEntity("PolarBear", EntityPolarBear.class); Entity.registerEntity("Pig", EntityPig.class); Entity.registerEntity("Rabbit", EntityRabbit.class); Entity.registerEntity("Sheep", EntitySheep.class); Entity.registerEntity("Squid", EntitySquid.class); Entity.registerEntity("Wolf", EntityWolf.class); Entity.registerEntity("Ocelot", EntityOcelot.class); Entity.registerEntity("Villager", EntityVillager.class); Entity.registerEntity("ThrownExpBottle", EntityExpBottle.class); Entity.registerEntity("XpOrb", EntityXPOrb.class); Entity.registerEntity("ThrownPotion", EntityPotion.class); Entity.registerEntity("Egg", EntityEgg.class); Entity.registerEntity("Human", EntityHuman.class, true); Entity.registerEntity("MinecartRideable", EntityMinecartEmpty.class); // TODO: 2016/1/30 all finds of minecart Entity.registerEntity("Boat", EntityBoat.class); //Entity.registerEntity("Lightning", EntityLightning.class); lightning shouldn't be saved as entity } private void registerBlockEntities() { BlockEntity.registerBlockEntity(BlockEntity.FURNACE, BlockEntityFurnace.class); BlockEntity.registerBlockEntity(BlockEntity.CHEST, BlockEntityChest.class); BlockEntity.registerBlockEntity(BlockEntity.SIGN, BlockEntitySign.class); BlockEntity.registerBlockEntity(BlockEntity.ENCHANT_TABLE, BlockEntityEnchantTable.class); BlockEntity.registerBlockEntity(BlockEntity.SKULL, BlockEntitySkull.class); BlockEntity.registerBlockEntity(BlockEntity.FLOWER_POT, BlockEntityFlowerPot.class); BlockEntity.registerBlockEntity(BlockEntity.BREWING_STAND, BlockEntityBrewingStand.class); BlockEntity.registerBlockEntity(BlockEntity.ITEM_FRAME, BlockEntityItemFrame.class); BlockEntity.registerBlockEntity(BlockEntity.CAULDRON, BlockEntityCauldron.class); BlockEntity.registerBlockEntity(BlockEntity.ENDER_CHEST, BlockEntityEnderChest.class); BlockEntity.registerBlockEntity(BlockEntity.BEACON, BlockEntityBeacon.class); BlockEntity.registerBlockEntity(BlockEntity.PISTON_ARM, BlockEntityPistonArm.class); BlockEntity.registerBlockEntity(BlockEntity.COMPARATOR, BlockEntityComparator.class); BlockEntity.registerBlockEntity(BlockEntity.HOPPER, BlockEntityHopper.class); BlockEntity.registerBlockEntity(BlockEntity.BED, BlockEntityBed.class); BlockEntity.registerBlockEntity(BlockEntity.JUKEBOX, BlockEntityJukebox.class); } public static Server getInstance() { return instance; } }
74,501
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
OfflinePlayer.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/OfflinePlayer.java
package cn.nukkit; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.plugin.Plugin; import java.io.File; import java.util.List; /** * 描述一个不在线的玩家的类。<br> * Describes an offline player. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.Player * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public class OfflinePlayer implements IPlayer { private final String name; private final Server server; private final CompoundTag namedTag; /** * 初始化这个{@code OfflinePlayer}对象。<br> * Initializes the object {@code OfflinePlayer}. * * @param server 这个玩家所在服务器的{@code Server}对象。<br> * The server this player is in, as a {@code Server} object. * @param name 这个玩家所的名字。<br> * Name of this player. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public OfflinePlayer(Server server, String name) { this.server = server; this.name = name; if (new File(this.server.getDataPath() + "players/" + name.toLowerCase() + ".dat").exists()) { this.namedTag = this.server.getOfflinePlayerData(this.name); } else { this.namedTag = null; } } @Override public boolean isOnline() { return this.getPlayer() != null; } @Override public String getName() { return name; } public Server getServer() { return server; } @Override public boolean isOp() { return this.server.isOp(this.getName().toLowerCase()); } @Override public void setOp(boolean value) { if (value == this.isOp()) { return; } if (value) { this.server.addOp(this.getName().toLowerCase()); } else { this.server.removeOp(this.getName().toLowerCase()); } } @Override public boolean isBanned() { return this.server.getNameBans().isBanned(this.getName()); } @Override public void setBanned(boolean value) { if (value) { this.server.getNameBans().addBan(this.getName(), null, null, null); } else { this.server.getNameBans().remove(this.getName()); } } @Override public boolean isWhitelisted() { return this.server.isWhitelisted(this.getName().toLowerCase()); } @Override public void setWhitelisted(boolean value) { if (value) { this.server.addWhitelist(this.getName().toLowerCase()); } else { this.server.removeWhitelist(this.getName().toLowerCase()); } } @Override public Player getPlayer() { return this.server.getPlayerExact(this.getName()); } @Override public Long getFirstPlayed() { return this.namedTag != null ? this.namedTag.getLong("firstPlayed") : null; } @Override public Long getLastPlayed() { return this.namedTag != null ? this.namedTag.getLong("lastPlayed") : null; } @Override public boolean hasPlayedBefore() { return this.namedTag != null; } public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { this.server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); } public List<MetadataValue> getMetadata(String metadataKey) { return this.server.getPlayerMetadata().getMetadata(this, metadataKey); } public boolean hasMetadata(String metadataKey) { return this.server.getPlayerMetadata().hasMetadata(this, metadataKey); } public void removeMetadata(String metadataKey, Plugin owningPlugin) { this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); } }
3,896
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Achievement.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/Achievement.java
package cn.nukkit; import cn.nukkit.utils.TextFormat; import java.util.HashMap; /** * Created by CreeperFace on 9. 11. 2016. */ public class Achievement { public static final HashMap<String, Achievement> achievements = new HashMap<String, Achievement>() { { put("mineWood", new Achievement("Getting Wood")); put("buildWorkBench", new Achievement("Benchmarking", "mineWood")); put("buildPickaxe", new Achievement("Time to Mine!", "buildWorkBench")); put("buildFurnace", new Achievement("Hot Topic", "buildPickaxe")); put("acquireIron", new Achievement("Acquire hardware", "buildFurnace")); put("buildHoe", new Achievement("Time to Farm!", "buildWorkBench")); put("makeBread", new Achievement("Bake Bread", "buildHoe")); put("bakeCake", new Achievement("The Lie", "buildHoe")); put("buildBetterPickaxe", new Achievement("Getting an Upgrade", "buildPickaxe")); put("buildSword", new Achievement("Time to Strike!", "buildWorkBench")); put("diamonds", new Achievement("DIAMONDS!", "acquireIron")); } }; public static boolean broadcast(Player player, String achievementId) { if (!achievements.containsKey(achievementId)) { return false; } String translation = Server.getInstance().getLanguage().translateString("chat.type.achievement", player.getDisplayName(), TextFormat.GREEN + achievements.get(achievementId).getMessage()); if (Server.getInstance().getPropertyBoolean("announce-player-achievements", true)) { Server.getInstance().broadcastMessage(translation); } else { player.sendMessage(translation); } return true; } public static boolean add(String name, Achievement achievement) { if (achievements.containsKey(name)) { return false; } achievements.put(name, achievement); return true; } public final String message; public final String[] requires; public Achievement(String message, String... requires) { this.message = message; this.requires = requires; } public String getMessage() { return message; } public void broadcast(Player player) { String translation = Server.getInstance().getLanguage().translateString("chat.type.achievement", player.getDisplayName(), TextFormat.GREEN + this.getMessage(), null); if (Server.getInstance().getPropertyBoolean("announce-player-achievements", true)) { Server.getInstance().broadcastMessage(translation); } else { player.sendMessage(translation); } } }
2,731
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
IPlayer.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/IPlayer.java
package cn.nukkit; import cn.nukkit.metadata.Metadatable; import cn.nukkit.permission.ServerOperator; /** * 用来描述一个玩家和获得这个玩家相应信息的接口。<br> * An interface to describe a player and get its information. * <p> * <p>这个玩家可以在线,也可以是不在线。<br> * This player can be online or offline.</p> * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.Player * @see cn.nukkit.OfflinePlayer * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface IPlayer extends ServerOperator, Metadatable { /** * 返回这个玩家是否在线。<br> * Returns if this player is online. * * @return 这个玩家是否在线。<br>If this player is online. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isOnline(); /** * 返回这个玩家的名称。<br> * Returns the name of this player. * <p> * <p>如果是在线的玩家,这个函数只会返回登录名字。如果要返回显示的名字,参见{@link cn.nukkit.Player#getDisplayName}<br> * Notice that this will only return its login name. If you need its display name, turn to * {@link cn.nukkit.Player#getDisplayName}</p> * * @return 这个玩家的名称。<br>The name of this player. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ String getName(); /** * 返回这个玩家是否被封禁(ban)。<br> * Returns if this player is banned. * * @return 这个玩家的名称。<br>The name of this player. * @see #setBanned * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isBanned(); /** * 设置这个玩家是否被封禁(ban)。<br> * Sets this player to be banned or to be pardoned. * * @param value 如果为{@code true},封禁这个玩家。如果为{@code false},解封这个玩家。<br> * {@code true} for ban and {@code false} for pardon. * @see #isBanned * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void setBanned(boolean value); /** * 返回这个玩家是否已加入白名单。<br> * Returns if this player is pardoned by whitelist. * * @return 这个玩家是否已加入白名单。<br>If this player is pardoned by whitelist. * @see cn.nukkit.Server#isWhitelisted * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isWhitelisted(); /** * 把这个玩家加入白名单,或者取消这个玩家的白名单。<br> * Adds this player to the white list, or removes it from the whitelist. * * @param value 如果为{@code true},把玩家加入白名单。如果为{@code false},取消这个玩家的白名单。<br> * {@code true} for add and {@code false} for remove. * @see #isWhitelisted * @see cn.nukkit.Server#addWhitelist * @see cn.nukkit.Server#removeWhitelist * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void setWhitelisted(boolean value); /** * 得到这个接口的{@code Player}对象。<br> * Returns a {@code Player} object for this interface. * * @return 这个接口的 {@code Player}对象。<br>a {@code Player} object for this interface. * @see cn.nukkit.Server#getPlayerExact * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Player getPlayer(); /** * 返回玩家所在的服务器。<br> * Returns the server carrying this player. * * @return 玩家所在的服务器。<br>the server carrying this player. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Server getServer(); /** * 得到这个玩家第一次游戏的时间。<br> * Returns the time this player first played in this server. * * @return 这个玩家第一次游戏的时间。<br>The time this player first played in this server. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Long getFirstPlayed(); /** * 得到这个玩家上次加入游戏的时间。<br> * Returns the time this player last joined in this server. * * @return 这个玩家上次游戏的时间。<br>The time this player last joined in this server. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Long getLastPlayed(); /** * 返回这个玩家以前是否来过服务器。<br> * Returns if this player has played in this server before. * <p> * <p>如果想得到这个玩家是不是第一次玩,可以使用:<br> * If you want to know if this player is the first time playing in this server, you can use:<br> * <pre>if(!player.hasPlayerBefore()) {...}</pre></p> * * @return 这个玩家以前是不是玩过游戏。<br>If this player has played in this server before. * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean hasPlayedBefore(); }
4,919
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Player.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/Player.java
package cn.nukkit; import cn.nukkit.AdventureSettings.Type; import cn.nukkit.block.*; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityItemFrame; import cn.nukkit.blockentity.BlockEntitySpawnable; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandDataVersions; import cn.nukkit.entity.*; import cn.nukkit.entity.data.*; import cn.nukkit.entity.item.*; import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.event.block.ItemFrameDropItemEvent; import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityDamageEvent.DamageModifier; import cn.nukkit.event.inventory.InventoryCloseEvent; import cn.nukkit.event.inventory.InventoryPickupArrowEvent; import cn.nukkit.event.inventory.InventoryPickupItemEvent; import cn.nukkit.event.player.*; import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.event.player.PlayerTeleportEvent.TeleportCause; import cn.nukkit.event.server.DataPacketReceiveEvent; import cn.nukkit.event.server.DataPacketSendEvent; import cn.nukkit.form.window.FormWindow; import cn.nukkit.form.window.FormWindowCustom; import cn.nukkit.inventory.*; import cn.nukkit.inventory.transaction.CraftingTransaction; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.data.ReleaseItemData; import cn.nukkit.inventory.transaction.data.UseItemData; import cn.nukkit.inventory.transaction.data.UseItemOnEntityData; import cn.nukkit.item.*; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.item.food.Food; import cn.nukkit.lang.TextContainer; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.level.*; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.particle.CriticalParticle; import cn.nukkit.level.particle.PunchBlockParticle; import cn.nukkit.math.*; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.*; import cn.nukkit.network.SourceInterface; import cn.nukkit.network.protocol.*; import cn.nukkit.network.protocol.types.ContainerIds; import cn.nukkit.network.protocol.types.NetworkInventoryAction; import cn.nukkit.permission.PermissibleBase; import cn.nukkit.permission.Permission; import cn.nukkit.permission.PermissionAttachment; import cn.nukkit.permission.PermissionAttachmentInfo; import cn.nukkit.plugin.Plugin; import cn.nukkit.potion.Effect; import cn.nukkit.potion.Potion; import cn.nukkit.resourcepacks.ResourcePack; import cn.nukkit.utils.*; import co.aikar.timings.Timing; import co.aikar.timings.Timings; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongIterator; import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.awt.*; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteOrder; import java.util.*; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; /** * author: MagicDroidX & Box * Nukkit Project */ public class Player extends EntityHuman implements CommandSender, InventoryHolder, ChunkLoader, IPlayer { public static final int SURVIVAL = 0; public static final int CREATIVE = 1; public static final int ADVENTURE = 2; public static final int SPECTATOR = 3; public static final int VIEW = SPECTATOR; public static final int SURVIVAL_SLOTS = 36; public static final int CREATIVE_SLOTS = 112; public static final int CRAFTING_SMALL = 0; public static final int CRAFTING_BIG = 1; public static final int CRAFTING_ANVIL = 2; public static final int CRAFTING_ENCHANT = 3; public static final float DEFAULT_SPEED = 0.1f; public static final float MAXIMUM_SPEED = 0.5f; public static final int PERMISSION_CUSTOM = 3; public static final int PERMISSION_OPERATOR = 2; public static final int PERMISSION_MEMBER = 1; public static final int PERMISSION_VISITOR = 0; public static final int ANVIL_WINDOW_ID = 2; public static final int ENCHANT_WINDOW_ID = 3; protected final SourceInterface interfaz; public boolean playedBefore; public boolean spawned = false; public boolean loggedIn = false; public int gamemode; public long lastBreak; protected int windowCnt = 4; protected Map<Inventory, Integer> windows; protected final Map<Integer, Inventory> windowIndex = new HashMap<>(); protected final Set<Integer> permanentWindows = new HashSet<>(); protected int messageCounter = 2; private String clientSecret; public Vector3 speed = null; public final HashSet<String> achievements = new HashSet<>(); public int craftingType = CRAFTING_SMALL; protected PlayerCursorInventory cursorInventory; protected CraftingGrid craftingGrid; protected CraftingTransaction craftingTransaction; public long creationTime = 0; protected long randomClientId; protected Vector3 forceMovement = null; protected Vector3 teleportPosition = null; protected boolean connected = true; protected final String ip; protected boolean removeFormat = true; protected final int port; protected String username; protected String iusername; protected String displayName; protected int startAction = -1; protected Vector3 sleeping = null; protected Long clientID = null; private Integer loaderId = null; protected float stepHeight = 0.6f; public final Map<Long, Boolean> usedChunks = new Long2ObjectOpenHashMap<>(); protected int chunkLoadCount = 0; protected final Long2ObjectLinkedOpenHashMap<Boolean> loadQueue = new Long2ObjectLinkedOpenHashMap<>(); protected int nextChunkOrderRun = 1; protected final Map<UUID, Player> hiddenPlayers = new HashMap<>(); protected Vector3 newPosition = null; protected int chunkRadius; protected int viewDistance; protected final int chunksPerTick; protected final int spawnThreshold; protected Position spawnPosition = null; protected int inAirTicks = 0; protected int startAirTicks = 5; protected AdventureSettings adventureSettings; protected boolean checkMovement = true; private final Int2ObjectOpenHashMap<Boolean> needACK = new Int2ObjectOpenHashMap<>(); private final Map<Integer, List<DataPacket>> batchedPackets = new TreeMap<>(); private PermissibleBase perm = null; private int exp = 0; private int expLevel = 0; protected PlayerFood foodData = null; private Entity killer = null; private final AtomicReference<Locale> locale = new AtomicReference<>(null); private int hash; private String buttonText = "Button"; protected boolean enableClientCommand = true; private BlockEnderChest viewingEnderChest = null; protected int lastEnderPearl = -1; private LoginChainData loginChainData; public Block breakingBlock = null; public int pickedXPOrb = 0; protected int formWindowCount = 0; protected Map<Integer, FormWindow> formWindows = new HashMap<>(); protected Map<Integer, FormWindow> serverSettings = new HashMap<>(); protected Map<Long, DummyBossBar> dummyBossBars = new HashMap<>(); public int getStartActionTick() { return startAction; } public void startAction() { this.startAction = this.server.getTick(); } public void stopAction() { this.startAction = -1; } public int getLastEnderPearlThrowingTick() { return lastEnderPearl; } public void onThrowEnderPearl() { this.lastEnderPearl = this.server.getTick(); } public BlockEnderChest getViewingEnderChest() { return viewingEnderChest; } public void setViewingEnderChest(BlockEnderChest chest) { if (chest == null && this.viewingEnderChest != null) { this.viewingEnderChest.getViewers().remove(this); } else if (chest != null) { chest.getViewers().add(this); } this.viewingEnderChest = chest; } public TranslationContainer getLeaveMessage() { return new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.left", this.getDisplayName()); } public String getClientSecret() { return clientSecret; } /** * This might disappear in the future. * Please use getUniqueId() instead (IP + clientId + name combo, in the future it'll change to real UUID for online auth) */ @Deprecated public Long getClientId() { return randomClientId; } @Override public boolean isBanned() { return this.server.getNameBans().isBanned(this.getName()); } @Override public void setBanned(boolean value) { if (value) { this.server.getNameBans().addBan(this.getName(), null, null, null); this.kick(PlayerKickEvent.Reason.NAME_BANNED, "Banned by admin"); } else { this.server.getNameBans().remove(this.getName()); } } @Override public boolean isWhitelisted() { return this.server.isWhitelisted(this.getName().toLowerCase()); } @Override public void setWhitelisted(boolean value) { if (value) { this.server.addWhitelist(this.getName().toLowerCase()); } else { this.server.removeWhitelist(this.getName().toLowerCase()); } } @Override public Player getPlayer() { return this; } @Override public Long getFirstPlayed() { return this.namedTag != null ? this.namedTag.getLong("firstPlayed") : null; } @Override public Long getLastPlayed() { return this.namedTag != null ? this.namedTag.getLong("lastPlayed") : null; } @Override public boolean hasPlayedBefore() { return this.playedBefore; } public AdventureSettings getAdventureSettings() { return adventureSettings; } public void setAdventureSettings(AdventureSettings adventureSettings) { this.adventureSettings = adventureSettings.clone(this); this.adventureSettings.update(); } public void resetInAirTicks() { this.inAirTicks = 0; } @Deprecated public void setAllowFlight(boolean value) { this.getAdventureSettings().set(Type.ALLOW_FLIGHT, value); this.getAdventureSettings().update(); } @Deprecated public boolean getAllowFlight() { return this.getAdventureSettings().get(Type.ALLOW_FLIGHT); } public void setAllowModifyWorld(boolean value) { this.getAdventureSettings().set(Type.WORLD_IMMUTABLE, !value); this.getAdventureSettings().set(Type.BUILD_AND_MINE, value); this.getAdventureSettings().set(Type.WORLD_BUILDER, value); this.getAdventureSettings().update(); } public void setAllowInteract(boolean value) { setAllowInteract(value, value); } public void setAllowInteract(boolean value, boolean containers) { this.getAdventureSettings().set(Type.WORLD_IMMUTABLE, !value); this.getAdventureSettings().set(Type.DOORS_AND_SWITCHED, value); this.getAdventureSettings().set(Type.OPEN_CONTAINERS, containers); this.getAdventureSettings().update(); } @Deprecated public void setAutoJump(boolean value) { this.getAdventureSettings().set(Type.AUTO_JUMP, value); this.getAdventureSettings().update(); } @Deprecated public boolean hasAutoJump() { return this.getAdventureSettings().get(Type.AUTO_JUMP); } @Override public void spawnTo(Player player) { if (this.spawned && player.spawned && this.isAlive() && player.isAlive() && player.getLevel() == this.level && player.canSee(this) && !this.isSpectator()) { super.spawnTo(player); } } @Override public Server getServer() { return this.server; } public boolean getRemoveFormat() { return removeFormat; } public void setRemoveFormat() { this.setRemoveFormat(true); } public void setRemoveFormat(boolean remove) { this.removeFormat = remove; } public boolean canSee(Player player) { return !this.hiddenPlayers.containsKey(player.getUniqueId()); } public void hidePlayer(Player player) { if (this == player) { return; } this.hiddenPlayers.put(player.getUniqueId(), player); player.despawnFrom(this); } public void showPlayer(Player player) { if (this == player) { return; } this.hiddenPlayers.remove(player.getUniqueId()); if (player.isOnline()) { player.spawnTo(this); } } @Override public boolean canCollideWith(Entity entity) { return false; } @Override public void resetFallDistance() { super.resetFallDistance(); if (this.inAirTicks != 0) { this.startAirTicks = 5; } this.inAirTicks = 0; this.highestPosition = this.y; } @Override public boolean isOnline() { return this.connected && this.loggedIn; } @Override public boolean isOp() { return this.server.isOp(this.getName()); } @Override public void setOp(boolean value) { if (value == this.isOp()) { return; } if (value) { this.server.addOp(this.getName()); } else { this.server.removeOp(this.getName()); } this.recalculatePermissions(); this.getAdventureSettings().update(); this.sendCommandData(); } @Override public boolean isPermissionSet(String name) { return this.perm.isPermissionSet(name); } @Override public boolean isPermissionSet(Permission permission) { return this.perm.isPermissionSet(permission); } @Override public boolean hasPermission(String name) { return this.perm != null && this.perm.hasPermission(name); } @Override public boolean hasPermission(Permission permission) { return this.perm.hasPermission(permission); } @Override public PermissionAttachment addAttachment(Plugin plugin) { return this.addAttachment(plugin, null); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name) { return this.addAttachment(plugin, name, null); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, Boolean value) { return this.perm.addAttachment(plugin, name, value); } @Override public void removeAttachment(PermissionAttachment attachment) { this.perm.removeAttachment(attachment); } @Override public void recalculatePermissions() { this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); if (this.perm == null) { return; } this.perm.recalculatePermissions(); if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); } if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } if (this.isEnableClientCommand()) this.sendCommandData(); } public boolean isEnableClientCommand() { return this.enableClientCommand; } public void setEnableClientCommand(boolean enable) { this.enableClientCommand = enable; SetCommandsEnabledPacket pk = new SetCommandsEnabledPacket(); pk.enabled = enable; this.dataPacket(pk); if (enable) this.sendCommandData(); } public void sendCommandData() { AvailableCommandsPacket pk = new AvailableCommandsPacket(); Map<String, CommandDataVersions> data = new HashMap<>(); int count = 0; for (Command command : this.server.getCommandMap().getCommands().values()) { if (!command.testPermissionSilent(this)) { continue; } ++count; CommandDataVersions data0 = command.generateCustomCommandData(this); data.put(command.getName(), data0); } if (count > 0) { //TODO: structure checking pk.commands = data; int identifier = this.dataPacket(pk, true); // We *need* ACK so we can be sure that the client received the packet or not Thread t = new Thread() { public void run() { // We are going to wait 3 seconds, if after 3 seconds we didn't receive a reply from the client, resend the packet. try { Thread.sleep(3000); Boolean status = needACK.get(identifier); if ((status == null || !status) && isOnline()) { sendCommandData(); return; } } catch (InterruptedException e) { } } }; t.start(); } } @Override public Map<String, PermissionAttachmentInfo> getEffectivePermissions() { return this.perm.getEffectivePermissions(); } public Player(SourceInterface interfaz, Long clientID, String ip, int port) { super(null, new CompoundTag()); this.interfaz = interfaz; this.windows = new HashMap<>(); this.perm = new PermissibleBase(this); this.server = Server.getInstance(); this.lastBreak = Long.MAX_VALUE; this.ip = ip; this.port = port; this.clientID = clientID; this.loaderId = Level.generateChunkLoaderId(this); this.chunksPerTick = (int) this.server.getConfig("chunk-sending.per-tick", 4); this.spawnThreshold = (int) this.server.getConfig("chunk-sending.spawn-threshold", 56); this.spawnPosition = null; this.gamemode = this.server.getGamemode(); this.setLevel(this.server.getDefaultLevel()); this.viewDistance = this.server.getViewDistance(); this.chunkRadius = viewDistance; //this.newPosition = new Vector3(0, 0, 0); this.boundingBox = new SimpleAxisAlignedBB(0, 0, 0, 0, 0, 0); this.uuid = null; this.rawUUID = null; this.creationTime = System.currentTimeMillis(); } @Override protected void initEntity() { super.initEntity(); this.addDefaultWindows(); } public boolean isPlayer() { return true; } public void removeAchievement(String achievementId) { achievements.remove(achievementId); } public boolean hasAchievement(String achievementId) { return achievements.contains(achievementId); } public boolean isConnected() { return connected; } public String getDisplayName() { return this.displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; if (this.spawned) { this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), this.getSkin(), this.getLoginChainData().getXUID()); } } @Override public void setSkin(Skin skin) { super.setSkin(skin); if (this.spawned) { this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), skin, this.getLoginChainData().getXUID()); } } public String getAddress() { return this.ip; } public int getPort() { return port; } public Position getNextPosition() { return this.newPosition != null ? new Position(this.newPosition.x, this.newPosition.y, this.newPosition.z, this.level) : this.getPosition(); } public boolean isSleeping() { return this.sleeping != null; } public int getInAirTicks() { return this.inAirTicks; } /** * Returns whether the player is currently using an item (right-click and hold). * * @return bool */ public boolean isUsingItem() { return this.getDataFlag(DATA_FLAGS, DATA_FLAG_ACTION) && this.startAction > -1; } public void setUsingItem(boolean value) { this.startAction = value ? this.server.getTick() : -1; this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, value); } public String getButtonText() { return this.buttonText; } public void setButtonText(String text) { this.buttonText = text; this.setDataProperty(new StringEntityData(Entity.DATA_INTERACTIVE_TAG, this.buttonText)); } @Override protected boolean switchLevel(Level targetLevel) { Level oldLevel = this.level; if (super.switchLevel(targetLevel)) { for (long index : new ArrayList<>(this.usedChunks.keySet())) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); this.unloadChunk(chunkX, chunkZ, oldLevel); } this.usedChunks.clear(); SetTimePacket pk = new SetTimePacket(); pk.time = this.level.getTime(); this.dataPacket(pk); // TODO: Remove this hack int distance = this.viewDistance * 2 * 16 * 2; this.sendPosition(this.add(distance, 0, distance), this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); return true; } return false; } public void unloadChunk(int x, int z) { this.unloadChunk(x, z, null); } public void unloadChunk(int x, int z, Level level) { level = level == null ? this.level : level; long index = Level.chunkHash(x, z); if (this.usedChunks.containsKey(index)) { for (Entity entity : level.getChunkEntities(x, z).values()) { if (entity != this) { entity.despawnFrom(this); } } this.usedChunks.remove(index); } level.unregisterChunkLoader(this, x, z); this.loadQueue.remove(index); } public Position getSpawn() { if (this.spawnPosition != null && this.spawnPosition.getLevel() != null) { return this.spawnPosition; } else { return this.server.getDefaultLevel().getSafeSpawn(); } } public void sendChunk(int x, int z, DataPacket packet) { if (!this.connected) { return; } this.usedChunks.put(Level.chunkHash(x, z), Boolean.TRUE); this.chunkLoadCount++; this.dataPacket(packet); if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } } public void sendChunk(int x, int z, byte[] payload) { if (!this.connected) { return; } this.usedChunks.put(Level.chunkHash(x, z), true); this.chunkLoadCount++; FullChunkDataPacket pk = new FullChunkDataPacket(); pk.chunkX = x; pk.chunkZ = z; pk.data = payload; this.batchDataPacket(pk); if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } } protected void sendNextChunk() { if (!this.connected) { return; } Timings.playerChunkSendTimer.startTiming(); if (!loadQueue.isEmpty()) { int count = 0; ObjectIterator<Long2ObjectMap.Entry<Boolean>> iter = loadQueue.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { Long2ObjectMap.Entry<Boolean> entry = iter.next(); long index = entry.getLongKey(); if (count >= this.chunksPerTick) { break; } int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); ++count; this.usedChunks.put(index, false); this.level.registerChunkLoader(this, chunkX, chunkZ, false); if (!this.level.populateChunk(chunkX, chunkZ)) { if (this.spawned && this.teleportPosition == null) { continue; } else { break; } } iter.remove(); PlayerChunkRequestEvent ev = new PlayerChunkRequestEvent(this, chunkX, chunkZ); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.level.requestChunk(chunkX, chunkZ, this); } } } if (this.chunkLoadCount >= this.spawnThreshold && !this.spawned && this.teleportPosition == null) { this.doFirstSpawn(); } Timings.playerChunkSendTimer.stopTiming(); } protected void doFirstSpawn() { this.spawned = true; this.getAdventureSettings().update(); this.sendPotionEffects(this); this.sendData(this); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); SetTimePacket setTimePacket = new SetTimePacket(); setTimePacket.time = this.level.getTime(); this.dataPacket(setTimePacket); Position pos = this.level.getSafeSpawn(this); PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this, pos); this.server.getPluginManager().callEvent(respawnEvent); pos = respawnEvent.getRespawnPosition(); if (this.getHealth() <= 0) { RespawnPacket respawnPacket = new RespawnPacket(); pos = this.getSpawn(); respawnPacket.x = (float) pos.x; respawnPacket.y = (float) pos.y; respawnPacket.z = (float) pos.z; this.dataPacket(respawnPacket); } else { RespawnPacket respawnPacket = new RespawnPacket(); respawnPacket.x = (float) pos.x; respawnPacket.y = (float) pos.y; respawnPacket.z = (float) pos.z; this.dataPacket(respawnPacket); } this.sendPlayStatus(PlayStatusPacket.PLAYER_SPAWN); PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(this, new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.joined", new String[]{ this.getDisplayName() }) ); this.server.getPluginManager().callEvent(playerJoinEvent); if (playerJoinEvent.getJoinMessage().toString().trim().length() > 0) { this.server.broadcastMessage(playerJoinEvent.getJoinMessage()); } this.noDamageTicks = 60; this.getServer().sendRecipeList(this); if (this.gamemode == Player.SPECTATOR) { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = ContainerIds.CREATIVE; this.dataPacket(inventoryContentPacket); } else { inventory.sendCreativeContents(); } for (long index : this.usedChunks.keySet()) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); for (Entity entity : this.level.getChunkEntities(chunkX, chunkZ).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } int experience = this.getExperience(); if (experience != 0) { this.sendExperience(experience); } int level = this.getExperienceLevel(); if (level != 0) { this.sendExperienceLevel(this.getExperienceLevel()); } this.teleport(pos, null); // Prevent PlayerTeleportEvent during player spawn if (!this.isSpectator()) { this.spawnToAll(); } //todo Updater //Weather if (this.level.isRaining() || this.level.isThundering()) { this.getLevel().sendWeather(this); } this.getLevel().sendWeather(this); //FoodLevel PlayerFood food = this.getFoodData(); if (food.getLevel() != food.getMaxLevel()) { food.sendFoodLevel(); } } protected boolean orderChunks() { if (!this.connected) { return false; } Timings.playerChunkOrderTimer.startTiming(); this.nextChunkOrderRun = 200; loadQueue.clear(); Long2ObjectOpenHashMap<Boolean> lastChunk = new Long2ObjectOpenHashMap<>(this.usedChunks); int centerX = (int) this.x >> 4; int centerZ = (int) this.z >> 4; int radius = spawned ? this.chunkRadius : (int) Math.ceil(Math.sqrt(spawnThreshold)); int radiusSqr = radius * radius; long index; for (int x = 0; x <= radius; x++) { int xx = x * x; for (int z = 0; z <= x; z++) { int distanceSqr = xx + z * z; if (distanceSqr > radiusSqr) continue; /* Top right quadrant */ if(this.usedChunks.get(index = Level.chunkHash(centerX + x, centerZ + z)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Top left quadrant */ if(this.usedChunks.get(index = Level.chunkHash(centerX - x - 1, centerZ + z)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom right quadrant */ if(this.usedChunks.get(index = Level.chunkHash(centerX + x, centerZ - z - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom left quadrant */ if(this.usedChunks.get(index = Level.chunkHash(centerX - x - 1, centerZ - z - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); if(x != z){ /* Top right quadrant mirror */ if(this.usedChunks.get(index = Level.chunkHash(centerX + z, centerZ + x)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Top left quadrant mirror */ if(this.usedChunks.get(index = Level.chunkHash(centerX - z - 1, centerZ + x)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom right quadrant mirror */ if(this.usedChunks.get(index = Level.chunkHash(centerX + z, centerZ - x - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom left quadrant mirror */ if(this.usedChunks.get(index = Level.chunkHash(centerX - z - 1, centerZ - x - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); } } } LongIterator keys = lastChunk.keySet().iterator(); while (keys.hasNext()) { index = keys.nextLong(); this.unloadChunk(Level.getHashX(index), Level.getHashZ(index)); } Timings.playerChunkOrderTimer.stopTiming(); return true; } public boolean batchDataPacket(DataPacket packet) { if (!this.connected) { return false; } try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent event = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) { timing.stopTiming(); return false; } if (!this.batchedPackets.containsKey(packet.getChannel())) { this.batchedPackets.put(packet.getChannel(), new ArrayList<>()); } this.batchedPackets.get(packet.getChannel()).add(packet.clone()); } return true; } /** * 0 is true * -1 is false * other is identifer */ public boolean dataPacket(DataPacket packet) { return this.dataPacket(packet, false) != -1; } public int dataPacket(DataPacket packet, boolean needACK) { if (!this.connected) { return -1; } try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return -1; } Integer identifier = this.interfaz.putPacket(this, packet, needACK, false); if (needACK && identifier != null) { this.needACK.put(identifier, Boolean.FALSE); timing.stopTiming(); return identifier; } } return 0; } /** * 0 is true * -1 is false * other is identifer */ public boolean directDataPacket(DataPacket packet) { return this.directDataPacket(packet, false) != -1; } public int directDataPacket(DataPacket packet, boolean needACK) { if (!this.connected) { return -1; } try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return -1; } Integer identifier = this.interfaz.putPacket(this, packet, needACK, true); if (needACK && identifier != null) { this.needACK.put(identifier, Boolean.FALSE); timing.stopTiming(); return identifier; } } return 0; } public int getPing() { return this.interfaz.getNetworkLatency(this); } public boolean sleepOn(Vector3 pos) { if (!this.isOnline()) { return false; } for (Entity p : this.level.getNearbyEntities(this.boundingBox.grow(2, 1, 2), this)) { if (p instanceof Player) { if (((Player) p).sleeping != null && pos.distance(((Player) p).sleeping) <= 0.1) { return false; } } } PlayerBedEnterEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerBedEnterEvent(this, this.level.getBlock(pos))); if (ev.isCancelled()) { return false; } this.sleeping = pos.clone(); this.teleport(new Location(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, this.yaw, this.pitch, this.level), null); this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, (int) pos.x, (int) pos.y, (int) pos.z)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, true); this.setSpawn(pos); this.level.sleepTicks = 60; return true; } public void setSpawn(Vector3 pos) { Level level; if (!(pos instanceof Position)) { level = this.level; } else { level = ((Position) pos).getLevel(); } this.spawnPosition = new Position(pos.x, pos.y, pos.z, level); SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_PLAYER_SPAWN; pk.x = (int) this.spawnPosition.x; pk.y = (int) this.spawnPosition.y; pk.z = (int) this.spawnPosition.z; this.dataPacket(pk); } public void stopSleep() { if (this.sleeping != null) { this.server.getPluginManager().callEvent(new PlayerBedLeaveEvent(this, this.level.getBlock(this.sleeping))); this.sleeping = null; this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false); this.level.sleepTicks = 0; AnimatePacket pk = new AnimatePacket(); pk.eid = this.id; pk.action = 3; //Wake up this.dataPacket(pk); } } public boolean awardAchievement(String achievementId) { if (!Server.getInstance().getPropertyBoolean("achievements", true)) { return false; } Achievement achievement = Achievement.achievements.get(achievementId); if (achievement == null || hasAchievement(achievementId)) { return false; } for (String id : achievement.requires) { if (!this.hasAchievement(id)) { return false; } } PlayerAchievementAwardedEvent event = new PlayerAchievementAwardedEvent(this, achievementId); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) { return false; } this.achievements.add(achievementId); achievement.broadcast(this); return true; } public int getGamemode() { return gamemode; } /** * Returns a client-friendly gamemode of the specified real gamemode * This function takes care of handling gamemodes known to MCPE (as of 1.1.0.3, that includes Survival, Creative and Adventure) * <p> * TODO: remove this when Spectator Mode gets added properly to MCPE */ private static int getClientFriendlyGamemode(int gamemode) { gamemode &= 0x03; if (gamemode == Player.SPECTATOR) { return Player.CREATIVE; } return gamemode; } public boolean setGamemode(int gamemode) { return this.setGamemode(gamemode, false, null); } public boolean setGamemode(int gamemode, boolean clientSide) { return this.setGamemode(gamemode, clientSide, null); } public boolean setGamemode(int gamemode, boolean clientSide, AdventureSettings newSettings) { if (gamemode < 0 || gamemode > 3 || this.gamemode == gamemode) { return false; } if (newSettings == null) { newSettings = this.getAdventureSettings().clone(this); newSettings.set(Type.WORLD_IMMUTABLE, (gamemode & 0x02) > 0); newSettings.set(Type.BUILD_AND_MINE, (gamemode & 0x02) <= 0); newSettings.set(Type.WORLD_BUILDER, (gamemode & 0x02) <= 0); newSettings.set(Type.ALLOW_FLIGHT, (gamemode & 0x01) > 0); newSettings.set(Type.NO_CLIP, gamemode == 0x03); newSettings.set(Type.FLYING, gamemode == 0x03); } PlayerGameModeChangeEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerGameModeChangeEvent(this, gamemode, newSettings)); if (ev.isCancelled()) { return false; } this.gamemode = gamemode; if (this.isSpectator()) { this.keepMovement = true; this.despawnFromAll(); } else { this.keepMovement = false; this.spawnToAll(); } this.namedTag.putInt("playerGameType", this.gamemode); if (!clientSide) { SetPlayerGameTypePacket pk = new SetPlayerGameTypePacket(); pk.gamemode = getClientFriendlyGamemode(gamemode); this.dataPacket(pk); } this.setAdventureSettings(ev.getNewAdventureSettings()); if (this.isSpectator()) { this.getAdventureSettings().set(Type.FLYING, true); this.teleport(this.temporalVector.setComponents(this.x, this.y + 0.1, this.z)); InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; this.dataPacket(inventoryContentPacket); } else { if (this.isSurvival()) { this.getAdventureSettings().set(Type.FLYING, false); } InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; inventoryContentPacket.slots = Item.getCreativeItems().stream().toArray(Item[]::new); this.dataPacket(inventoryContentPacket); } this.resetFallDistance(); this.inventory.sendContents(this); this.inventory.sendContents(this.getViewers().values()); this.inventory.sendHeldItem(this.hasSpawned.values()); this.inventory.sendCreativeContents(); return true; } @Deprecated public void sendSettings() { this.getAdventureSettings().update(); } public boolean isSurvival() { return (this.gamemode & 0x01) == 0; } public boolean isCreative() { return (this.gamemode & 0x01) > 0; } public boolean isSpectator() { return this.gamemode == 3; } public boolean isAdventure() { return (this.gamemode & 0x02) > 0; } @Override public Item[] getDrops() { if (!this.isCreative()) { return super.getDrops(); } return new Item[0]; } @Override public boolean setDataProperty(EntityData data) { return setDataProperty(data, true); } @Override public boolean setDataProperty(EntityData data, boolean send) { if (super.setDataProperty(data, send)) { if (send) this.sendData(this, new EntityMetadata().put(this.getDataProperty(data.getId()))); return true; } return false; } @Override protected void checkGroundState(double movX, double movY, double movZ, double dx, double dy, double dz) { if (!this.onGround || movX != 0 || movY != 0 || movZ != 0) { boolean onGround = false; AxisAlignedBB bb = this.boundingBox.clone(); bb.setMaxY(bb.getMinY() + 0.5); bb.setMinY(bb.getMinY() - 1); AxisAlignedBB realBB = this.boundingBox.clone(); realBB.setMaxY(realBB.getMinY() + 0.1); realBB.setMinY(realBB.getMinY() - 0.2); int minX = NukkitMath.floorDouble(bb.getMinX()); int minY = NukkitMath.floorDouble(bb.getMinY()); int minZ = NukkitMath.floorDouble(bb.getMinZ()); int maxX = NukkitMath.ceilDouble(bb.getMaxX()); int maxY = NukkitMath.ceilDouble(bb.getMaxY()); int maxZ = NukkitMath.ceilDouble(bb.getMaxZ()); for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); if (!block.canPassThrough() && block.collidesWithBB(realBB)) { onGround = true; break; } } } } this.onGround = onGround; } this.isCollided = this.onGround; } @Override protected void checkBlockCollision() { boolean portal = false; for (Block block : this.getCollisionBlocks()) { if (block.getId() == Block.NETHER_PORTAL) { portal = true; continue; } block.onEntityCollide(this); } if (portal) { inPortalTicks++; } else { this.inPortalTicks = 0; } } protected void checkNearEntities() { for (Entity entity : this.level.getNearbyEntities(this.boundingBox.grow(1, 0.5, 1), this)) { entity.scheduleUpdate(); if (!entity.isAlive() || !this.isAlive()) { continue; } this.pickupEntity(entity, true); } } protected void processMovement(int tickDiff) { if (!this.isAlive() || !this.spawned || this.newPosition == null || this.teleportPosition != null || this.isSleeping()) { return; } Vector3 newPos = this.newPosition; double distanceSquared = newPos.distanceSquared(this); boolean revert = false; if ((distanceSquared / ((double) (tickDiff * tickDiff))) > 100 && (newPos.y - this.y) > -5) { revert = true; } else { if (this.chunk == null || !this.chunk.isGenerated()) { BaseFullChunk chunk = this.level.getChunk((int) newPos.x >> 4, (int) newPos.z >> 4, false); if (chunk == null || !chunk.isGenerated()) { revert = true; this.nextChunkOrderRun = 0; } else { if (this.chunk != null) { this.chunk.removeEntity(this); } this.chunk = chunk; } } } double tdx = newPos.x - this.x; double tdz = newPos.z - this.z; double distance = Math.sqrt(tdx * tdx + tdz * tdz); if (!revert && distanceSquared != 0) { double dx = newPos.x - this.x; double dy = newPos.y - this.y; double dz = newPos.z - this.z; this.fastMove(dx, dy, dz); if (this.newPosition == null) { return; //maybe solve that in better way } double diffX = this.x - newPos.x; double diffY = this.y - newPos.y; double diffZ = this.z - newPos.z; double yS = 0.5 + this.ySize; if (diffY >= -yS || diffY <= yS) { diffY = 0; } if (diffX != 0 || diffY != 0 || diffZ != 0) { if (this.checkMovement && !server.getAllowFlight() && this.isSurvival()) { // Some say: I cant move my head when riding because the server // blocked my movement if (!this.isSleeping() && this.riding == null) { double diffHorizontalSqr = (diffX * diffX + diffZ * diffZ) / ((double) (tickDiff * tickDiff)); if (diffHorizontalSqr > 0.125) { PlayerInvalidMoveEvent ev; this.getServer().getPluginManager().callEvent(ev = new PlayerInvalidMoveEvent(this, true)); if (!ev.isCancelled()) { revert = ev.isRevert(); if (revert) { this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidMove", this.getName())); } } } } } this.x = newPos.x; this.y = newPos.y; this.z = newPos.z; double radius = this.getWidth() / 2; this.boundingBox.setBounds(this.x - radius, this.y, this.z - radius, this.x + radius, this.y + this.getHeight(), this.z + radius); } } Location from = new Location( this.lastX, this.lastY, this.lastZ, this.lastYaw, this.lastPitch, this.level); Location to = this.getLocation(); double delta = Math.pow(this.lastX - to.x, 2) + Math.pow(this.lastY - to.y, 2) + Math.pow(this.z - to.z, 2); double deltaAngle = Math.abs(this.lastYaw - to.yaw) + Math.abs(this.lastPitch - to.pitch); if (!revert && (delta > 0.0001d || deltaAngle > 1d)) { boolean isFirst = this.firstMove; this.firstMove = false; this.lastX = to.x; this.lastY = to.y; this.lastZ = to.z; this.lastYaw = to.yaw; this.lastPitch = to.pitch; if (!isFirst) { List<Block> blocksAround = new ArrayList<>(this.blocksAround); List<Block> collidingBlocks = new ArrayList<>(this.collisionBlocks); PlayerMoveEvent ev = new PlayerMoveEvent(this, from, to); this.blocksAround = null; this.collisionBlocks = null; this.server.getPluginManager().callEvent(ev); if (!(revert = ev.isCancelled())) { //Yes, this is intended if (!to.equals(ev.getTo())) { //If plugins modify the destination this.teleport(ev.getTo(), null); } else { this.addMovement(this.x, this.y + this.getEyeHeight(), this.z, this.yaw, this.pitch, this.yaw); } } else { this.blocksAround = blocksAround; this.collisionBlocks = collidingBlocks; } } if (!this.isSpectator()) { this.checkNearEntities(); } if (this.speed == null) speed = new Vector3(from.x - to.x, from.y - to.y, from.z - to.z); else this.speed.setComponents(from.x - to.x, from.y - to.y, from.z - to.z); } else { if (this.speed == null) speed = new Vector3(0, 0, 0); else this.speed.setComponents(0, 0, 0); } if (!revert && (this.isFoodEnabled() || this.getServer().getDifficulty() == 0)) { if ((this.isSurvival() || this.isAdventure())/* && !this.getRiddingOn() instanceof Entity*/) { //UpdateFoodExpLevel if (distance >= 0.05) { double jump = 0; double swimming = this.isInsideOfWater() ? 0.015 * distance : 0; if (swimming != 0) distance = 0; if (this.isSprinting()) { //Running if (this.inAirTicks == 3 && swimming == 0) { jump = 0.7; } this.getFoodData().updateFoodExpLevel(0.1 * distance + jump + swimming); } else { if (this.inAirTicks == 3 && swimming == 0) { jump = 0.2; } this.getFoodData().updateFoodExpLevel(0.01 * distance + jump + swimming); } } } } if (revert) { this.lastX = from.x; this.lastY = from.y; this.lastZ = from.z; this.lastYaw = from.yaw; this.lastPitch = from.pitch; this.sendPosition(from, from.yaw, from.pitch, MovePlayerPacket.MODE_RESET); //this.sendSettings(); this.forceMovement = new Vector3(from.x, from.y, from.z); } else { this.forceMovement = null; if (distanceSquared != 0 && this.nextChunkOrderRun > 20) { this.nextChunkOrderRun = 20; } } this.newPosition = null; } @Override public boolean setMotion(Vector3 motion) { if (super.setMotion(motion)) { if (this.chunk != null) { this.getLevel().addEntityMotion(this.chunk.getX(), this.chunk.getZ(), this.getId(), this.motionX, this.motionY, this.motionZ); //Send to others SetEntityMotionPacket pk = new SetEntityMotionPacket(); pk.eid = this.id; pk.motionX = (float) motion.x; pk.motionY = (float) motion.y; pk.motionZ = (float) motion.z; this.dataPacket(pk); //Send to self } if (this.motionY > 0) { //todo: check this this.startAirTicks = (int) ((-(Math.log(this.getGravity() / (this.getGravity() + this.getDrag() * this.motionY))) / this.getDrag()) * 2 + 5); } return true; } return false; } public void sendAttributes() { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entityId = this.getId(); pk.entries = new Attribute[]{ Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0), Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(this.getFoodData().getLevel()), Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(this.getMovementSpeed()), Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(this.getExperienceLevel()), Attribute.getAttribute(Attribute.EXPERIENCE).setValue(((float) this.getExperience()) / calculateRequireExperience(this.getExperienceLevel())) }; this.dataPacket(pk); } @Override public boolean onUpdate(int currentTick) { if (!this.loggedIn) { return false; } int tickDiff = currentTick - this.lastUpdate; if (tickDiff <= 0) { return true; } this.messageCounter = 2; this.lastUpdate = currentTick; if (!this.isAlive() && this.spawned) { ++this.deadTicks; if (this.deadTicks >= 10) { this.despawnFromAll(); } return true; } if (this.spawned) { this.processMovement(tickDiff); this.entityBaseTick(tickDiff); if (this.getServer().getDifficulty() == 0 && this.level.getGameRules().getBoolean(GameRule.NATURAL_REGENERATION)) { if (this.getHealth() < this.getMaxHealth() && this.ticksLived % 20 == 0) { this.heal(1); } PlayerFood foodData = this.getFoodData(); if (foodData.getLevel() < 20 && this.ticksLived % 10 == 0) { foodData.addFoodLevel(1, 0); } } if (this.isOnFire() && this.lastUpdate % 10 == 0) { if (this.isCreative() && !this.isInsideOfFire()) { this.extinguish(); } else if (this.getLevel().isRaining()) { if (this.getLevel().canBlockSeeSky(this)) { this.extinguish(); } } } if (!this.isSpectator() && this.speed != null) { if (this.onGround) { if (this.inAirTicks != 0) { this.startAirTicks = 5; } this.inAirTicks = 0; this.highestPosition = this.y; } else { if (!this.isGliding() && !server.getAllowFlight() && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && this.inAirTicks > 10 && !this.isSleeping() && !this.isImmobile()) { double expectedVelocity = (-this.getGravity()) / ((double) this.getDrag()) - ((-this.getGravity()) / ((double) this.getDrag())) * Math.exp(-((double) this.getDrag()) * ((double) (this.inAirTicks - this.startAirTicks))); double diff = (this.speed.y - expectedVelocity) * (this.speed.y - expectedVelocity); if (!this.hasEffect(Effect.JUMP) && diff > 0.6 && expectedVelocity < this.speed.y) { if (this.inAirTicks < 100) { //this.sendSettings(); this.setMotion(new Vector3(0, expectedVelocity, 0)); } else if (this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server")) { return false; } } } if (this.y > highestPosition) { this.highestPosition = this.y; } if (this.isGliding()) this.resetFallDistance(); ++this.inAirTicks; } if (this.isSurvival() || this.isAdventure()) { if (this.getFoodData() != null) this.getFoodData().update(tickDiff); } } } this.checkTeleportPosition(); this.checkInteractNearby(); if (this.spawned && this.dummyBossBars.size() > 0 && currentTick % 100 == 0) { this.dummyBossBars.values().forEach(DummyBossBar::updateBossEntityPosition); } return true; } public void checkInteractNearby() { int interactDistance = isCreative() ? 5 : 3; if (canInteract(this, interactDistance)) { if (getEntityPlayerLookingAt(interactDistance) != null) { EntityInteractable onInteract = getEntityPlayerLookingAt(interactDistance); setButtonText(onInteract.getInteractButtonText()); } else { setButtonText(""); } } else { setButtonText(""); } } /** * Returns the Entity the player is looking at currently * * @param maxDistance the maximum distance to check for entities * @return Entity|null either NULL if no entity is found or an instance of the entity */ public EntityInteractable getEntityPlayerLookingAt(int maxDistance) { timing.startTiming(); EntityInteractable entity = null; // just a fix because player MAY not be fully initialized if (temporalVector != null) { Entity[] nearbyEntities = level.getNearbyEntities(boundingBox.grow(maxDistance, maxDistance, maxDistance), this); // get all blocks in looking direction until the max interact distance is reached (it's possible that startblock isn't found!) try { BlockIterator itr = new BlockIterator(level, getPosition(), getDirectionVector(), getEyeHeight(), maxDistance); if (itr.hasNext()) { Block block; while (itr.hasNext()) { block = itr.next(); entity = getEntityAtPosition(nearbyEntities, block.getFloorX(), block.getFloorY(), block.getFloorZ()); if (entity != null) { break; } } } } catch (Exception ex) { // nothing to log here! } } timing.stopTiming(); return entity; } private EntityInteractable getEntityAtPosition(Entity[] nearbyEntities, int x, int y, int z) { for (Entity nearestEntity : nearbyEntities) { if (nearestEntity.getFloorX() == x && nearestEntity.getFloorY() == y && nearestEntity.getFloorZ() == z && nearestEntity instanceof EntityInteractable && ((EntityInteractable) nearestEntity).canDoInteraction()) { return (EntityInteractable) nearestEntity; } } return null; } public void checkNetwork() { if (!this.isOnline()) { return; } if (!this.batchedPackets.isEmpty()) { Player[] pArr = new Player[]{this}; Iterator<Entry<Integer, List<DataPacket>>> iter = this.batchedPackets.entrySet().iterator(); while (iter.hasNext()) { Entry<Integer, List<DataPacket>> entry = iter.next(); List<DataPacket> packets = entry.getValue(); DataPacket[] arr = packets.toArray(new DataPacket[packets.size()]); packets.clear(); this.server.batchPackets(pArr, arr, false); } this.batchedPackets.clear(); } if (this.nextChunkOrderRun-- <= 0 || this.chunk == null) { this.orderChunks(); } if (!this.loadQueue.isEmpty() || !this.spawned) { this.sendNextChunk(); } } public boolean canInteract(Vector3 pos, double maxDistance) { return this.canInteract(pos, maxDistance, 0.5); } public boolean canInteract(Vector3 pos, double maxDistance, double maxDiff) { if (this.distanceSquared(pos) > maxDistance * maxDistance) { return false; } Vector2 dV = this.getDirectionPlane(); double dot = dV.dot(new Vector2(this.x, this.z)); double dot1 = dV.dot(new Vector2(pos.x, pos.z)); return (dot1 - dot) >= -maxDiff; } protected void processLogin() { if (!this.server.isWhitelisted((this.getName()).toLowerCase())) { this.kick(PlayerKickEvent.Reason.NOT_WHITELISTED, "Server is white-listed"); return; } else if (this.isBanned()) { this.kick(PlayerKickEvent.Reason.NAME_BANNED, "You are banned"); return; } else if (this.server.getIPBans().isBanned(this.getAddress())) { this.kick(PlayerKickEvent.Reason.IP_BANNED, "You are banned"); return; } if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); } if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } for (Player p : new ArrayList<>(this.server.getOnlinePlayers().values())) { if (p != this && p.getName() != null && p.getName().equalsIgnoreCase(this.getName())) { if (!p.kick(PlayerKickEvent.Reason.NEW_CONNECTION, "logged in from another location")) { this.close(this.getLeaveMessage(), "Already connected"); return; } } else if (p.loggedIn && this.getUniqueId().equals(p.getUniqueId())) { if (!p.kick(PlayerKickEvent.Reason.NEW_CONNECTION, "logged in from another location")) { this.close(this.getLeaveMessage(), "Already connected"); return; } } } CompoundTag nbt = this.server.getOfflinePlayerData(this.username); if (nbt == null) { this.close(this.getLeaveMessage(), "Invalid data"); return; } this.playedBefore = (nbt.getLong("lastPlayed") - nbt.getLong("firstPlayed")) > 1; boolean alive = true; nbt.putString("NameTag", this.username); if (0 >= nbt.getShort("Health")) { alive = false; } int exp = nbt.getInt("EXP"); int expLevel = nbt.getInt("expLevel"); this.setExperience(exp, expLevel); this.gamemode = nbt.getInt("playerGameType") & 0x03; if (this.server.getForceGamemode()) { this.gamemode = this.server.getGamemode(); nbt.putInt("playerGameType", this.gamemode); } this.adventureSettings = new AdventureSettings(this) .set(Type.WORLD_IMMUTABLE, isAdventure()) .set(Type.WORLD_BUILDER, !isAdventure()) .set(Type.AUTO_JUMP, true) .set(Type.ALLOW_FLIGHT, isCreative()) .set(Type.NO_CLIP, isSpectator()); Level level; if ((level = this.server.getLevelByName(nbt.getString("Level"))) == null || !alive) { this.setLevel(this.server.getDefaultLevel()); nbt.putString("Level", this.level.getName()); nbt.getList("Pos", DoubleTag.class) .add(new DoubleTag("0", this.level.getSpawnLocation().x)) .add(new DoubleTag("1", this.level.getSpawnLocation().y)) .add(new DoubleTag("2", this.level.getSpawnLocation().z)); } else { this.setLevel(level); } for (Tag achievement : nbt.getCompound("Achievements").getAllTags()) { if (!(achievement instanceof ByteTag)) { continue; } if (((ByteTag) achievement).getData() > 0) { this.achievements.add(achievement.getName()); } } nbt.putLong("lastPlayed", System.currentTimeMillis() / 1000); if (this.server.getAutoSave()) { this.server.saveOfflinePlayerData(this.username, nbt, true); } this.sendPlayStatus(PlayStatusPacket.LOGIN_SUCCESS); this.server.onPlayerLogin(this); ListTag<DoubleTag> posList = nbt.getList("Pos", DoubleTag.class); super.init(this.level.getChunk((int) posList.get(0).data >> 4, (int) posList.get(2).data >> 4, true), nbt); if (!this.namedTag.contains("foodLevel")) { this.namedTag.putInt("foodLevel", 20); } int foodLevel = this.namedTag.getInt("foodLevel"); if (!this.namedTag.contains("FoodSaturationLevel")) { this.namedTag.putFloat("FoodSaturationLevel", 20); } float foodSaturationLevel = this.namedTag.getFloat("foodSaturationLevel"); this.foodData = new PlayerFood(this, foodLevel, foodSaturationLevel); if (this.isSpectator()) this.keepMovement = true; this.forceMovement = this.teleportPosition = this.getPosition(); ResourcePacksInfoPacket infoPacket = new ResourcePacksInfoPacket(); infoPacket.resourcePackEntries = this.server.getResourcePackManager().getResourceStack(); infoPacket.mustAccept = this.server.getForceResources(); this.dataPacket(infoPacket); } protected void completeLoginSequence() { PlayerLoginEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerLoginEvent(this, "Plugin reason")); if (ev.isCancelled()) { this.close(this.getLeaveMessage(), ev.getKickMessage()); return; } Level level; if (this.spawnPosition == null && this.namedTag.contains("SpawnLevel") && (level = this.server.getLevelByName(this.namedTag.getString("SpawnLevel"))) != null) { this.spawnPosition = new Position(this.namedTag.getInt("SpawnX"), this.namedTag.getInt("SpawnY"), this.namedTag.getInt("SpawnZ"), level); } Position spawnPosition = this.getSpawn(); StartGamePacket startGamePacket = new StartGamePacket(); startGamePacket.entityUniqueId = this.id; startGamePacket.entityRuntimeId = this.id; startGamePacket.playerGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.x = (float) this.x; startGamePacket.y = (float) this.y; startGamePacket.z = (float) this.z; startGamePacket.yaw = (float) this.yaw; startGamePacket.pitch = (float) this.pitch; startGamePacket.seed = -1; startGamePacket.dimension = (byte) (spawnPosition.level.getDimension() & 0xff); startGamePacket.worldGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.difficulty = this.server.getDifficulty(); startGamePacket.spawnX = (int) spawnPosition.x; startGamePacket.spawnY = (int) spawnPosition.y; startGamePacket.spawnZ = (int) spawnPosition.z; startGamePacket.hasAchievementsDisabled = true; startGamePacket.dayCycleStopTime = -1; startGamePacket.eduMode = false; startGamePacket.rainLevel = 0; startGamePacket.lightningLevel = 0; startGamePacket.commandsEnabled = this.isEnableClientCommand(); startGamePacket.gameRules = getLevel().getGameRules(); startGamePacket.levelId = ""; startGamePacket.worldName = this.getServer().getNetwork().getName(); startGamePacket.generator = 1; //0 old, 1 infinite, 2 flat this.dataPacket(startGamePacket); this.loggedIn = true; spawnPosition.level.sendTime(this); this.setMovementSpeed(DEFAULT_SPEED); this.sendAttributes(); this.setNameTagVisible(true); this.setNameTagAlwaysVisible(true); this.setCanClimb(true); this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logIn", TextFormat.AQUA + this.username + TextFormat.WHITE, this.ip, String.valueOf(this.port), String.valueOf(this.id), this.level.getName(), String.valueOf(NukkitMath.round(this.x, 4)), String.valueOf(NukkitMath.round(this.y, 4)), String.valueOf(NukkitMath.round(this.z, 4)))); if (this.isOp()) { this.setRemoveFormat(false); } this.setEnableClientCommand(true); this.server.addOnlinePlayer(this); this.server.onPlayerCompleteLoginSequence(this); } public void handleDataPacket(DataPacket packet) { if (!connected) { return; } try (Timing timing = Timings.getReceiveDataPacketTiming(packet)) { DataPacketReceiveEvent ev = new DataPacketReceiveEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return; } if (packet.pid() == ProtocolInfo.BATCH_PACKET) { timing.stopTiming(); this.server.getNetwork().processBatch((BatchPacket) packet, this); return; } packetswitch: switch (packet.pid()) { case ProtocolInfo.LOGIN_PACKET: if (this.loggedIn) { break; } LoginPacket loginPacket = (LoginPacket) packet; String message; if (!ProtocolInfo.SUPPORTED_PROTOCOLS.contains(loginPacket.getProtocol())) { if (loginPacket.getProtocol() < ProtocolInfo.CURRENT_PROTOCOL) { message = "disconnectionScreen.outdatedClient"; this.sendPlayStatus(PlayStatusPacket.LOGIN_FAILED_CLIENT); } else { message = "disconnectionScreen.outdatedServer"; this.sendPlayStatus(PlayStatusPacket.LOGIN_FAILED_SERVER); } if (((LoginPacket) packet).protocol < 137) { DisconnectPacket disconnectPacket = new DisconnectPacket(); disconnectPacket.message = message; disconnectPacket.encode(); BatchPacket batch = new BatchPacket(); batch.payload = disconnectPacket.getBuffer(); this.directDataPacket(batch); // Still want to run close() to allow the player to be removed properly } this.close("", message, false); break; } this.username = TextFormat.clean(loginPacket.username); this.displayName = this.username; this.iusername = this.username.toLowerCase(); this.setDataProperty(new StringEntityData(DATA_NAMETAG, this.username), false); this.loginChainData = ClientChainData.read(loginPacket); if (!loginChainData.isXboxAuthed() && server.getPropertyBoolean("xbox-auth")) { kick(PlayerKickEvent.Reason.UNKNOWN, "disconnectionScreen.notAuthenticated", false); } if (this.server.getOnlinePlayers().size() >= this.server.getMaxPlayers() && this.kick(PlayerKickEvent.Reason.SERVER_FULL, "disconnectionScreen.serverFull", false)) { break; } this.randomClientId = loginPacket.clientId; this.uuid = loginPacket.clientUUID; this.rawUUID = Binary.writeUUID(this.uuid); boolean valid = true; int len = loginPacket.username.length(); if (len > 16 || len < 3) { valid = false; } for (int i = 0; i < len && valid; i++) { char c = loginPacket.username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == ' ' ) { continue; } valid = false; break; } if (!valid || Objects.equals(this.iusername, "rcon") || Objects.equals(this.iusername, "console")) { this.close("", "disconnectionScreen.invalidName"); break; } if (!loginPacket.skin.isValid()) { this.close("", "disconnectionScreen.invalidSkin"); break; } else { this.setSkin(loginPacket.getSkin()); } PlayerPreLoginEvent playerPreLoginEvent; this.server.getPluginManager().callEvent(playerPreLoginEvent = new PlayerPreLoginEvent(this, "Plugin reason")); if (playerPreLoginEvent.isCancelled()) { this.close("", playerPreLoginEvent.getKickMessage()); break; } this.processLogin(); break; case ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET: ResourcePackClientResponsePacket responsePacket = (ResourcePackClientResponsePacket) packet; switch (responsePacket.responseStatus) { case ResourcePackClientResponsePacket.STATUS_REFUSED: this.close("", "disconnectionScreen.noReason"); break; case ResourcePackClientResponsePacket.STATUS_SEND_PACKS: for (String id : responsePacket.packIds) { ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(id); if (resourcePack == null) { this.close("", "disconnectionScreen.resourcePack"); break; } ResourcePackDataInfoPacket dataInfoPacket = new ResourcePackDataInfoPacket(); dataInfoPacket.packId = resourcePack.getPackId(); dataInfoPacket.maxChunkSize = 1048576; //megabyte dataInfoPacket.chunkCount = resourcePack.getPackSize() / dataInfoPacket.maxChunkSize; dataInfoPacket.compressedPackSize = resourcePack.getPackSize(); dataInfoPacket.sha256 = resourcePack.getSha256(); this.dataPacket(dataInfoPacket); } break; case ResourcePackClientResponsePacket.STATUS_HAVE_ALL_PACKS: ResourcePackStackPacket stackPacket = new ResourcePackStackPacket(); stackPacket.mustAccept = this.server.getForceResources(); stackPacket.resourcePackStack = this.server.getResourcePackManager().getResourceStack(); this.dataPacket(stackPacket); break; case ResourcePackClientResponsePacket.STATUS_COMPLETED: this.completeLoginSequence(); break; } break; case ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET: ResourcePackChunkRequestPacket requestPacket = (ResourcePackChunkRequestPacket) packet; ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(requestPacket.packId); if (resourcePack == null) { this.close("", "disconnectionScreen.resourcePack"); break; } ResourcePackChunkDataPacket dataPacket = new ResourcePackChunkDataPacket(); dataPacket.packId = resourcePack.getPackId(); dataPacket.chunkIndex = requestPacket.chunkIndex; dataPacket.data = resourcePack.getPackChunk(1048576 * requestPacket.chunkIndex, 1048576); dataPacket.progress = 1048576 * requestPacket.chunkIndex; this.dataPacket(dataPacket); break; case ProtocolInfo.PLAYER_INPUT_PACKET: if (!this.isAlive() || !this.spawned) { break; } PlayerInputPacket ipk = (PlayerInputPacket) packet; if (riding instanceof EntityMinecartAbstract) { ((EntityMinecartEmpty) riding).setCurrentSpeed(ipk.motionY); } break; case ProtocolInfo.MOVE_PLAYER_PACKET: if (this.teleportPosition != null) { break; } MovePlayerPacket movePlayerPacket = (MovePlayerPacket) packet; Vector3 newPos = new Vector3(movePlayerPacket.x, movePlayerPacket.y - this.getEyeHeight(), movePlayerPacket.z); if (newPos.distanceSquared(this) < 0.01 && movePlayerPacket.yaw % 360 == this.yaw && movePlayerPacket.pitch % 360 == this.pitch) { break; } boolean revert = false; if (!this.isAlive() || !this.spawned) { revert = true; this.forceMovement = new Vector3(this.x, this.y, this.z); } if (this.forceMovement != null && (newPos.distanceSquared(this.forceMovement) > 0.1 || revert)) { this.sendPosition(this.forceMovement, movePlayerPacket.yaw, movePlayerPacket.pitch, MovePlayerPacket.MODE_RESET); } else { movePlayerPacket.yaw %= 360; movePlayerPacket.pitch %= 360; if (movePlayerPacket.yaw < 0) { movePlayerPacket.yaw += 360; } this.setRotation(movePlayerPacket.yaw, movePlayerPacket.pitch); this.newPosition = newPos; this.forceMovement = null; } if (riding != null) { if (riding instanceof EntityBoat) { riding.setPositionAndRotation(this.temporalVector.setComponents(movePlayerPacket.x, movePlayerPacket.y - 1, movePlayerPacket.z), (movePlayerPacket.headYaw + 90) % 360, 0); } } break; case ProtocolInfo.ADVENTURE_SETTINGS_PACKET: //TODO: player abilities, check for other changes AdventureSettingsPacket adventureSettingsPacket = (AdventureSettingsPacket) packet; if (adventureSettingsPacket.getFlag(AdventureSettingsPacket.ALLOW_FLIGHT) && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT)) { this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server"); break; } PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, adventureSettingsPacket.getFlag(AdventureSettingsPacket.ALLOW_FLIGHT)); this.server.getPluginManager().callEvent(playerToggleFlightEvent); if (playerToggleFlightEvent.isCancelled()) { this.getAdventureSettings().update(); } else { this.getAdventureSettings().set(Type.FLYING, playerToggleFlightEvent.isFlying()); } break; case ProtocolInfo.MOB_EQUIPMENT_PACKET: if (!this.spawned || !this.isAlive()) { break; } MobEquipmentPacket mobEquipmentPacket = (MobEquipmentPacket) packet; Item item = this.inventory.getItem(mobEquipmentPacket.hotbarSlot); if (!item.equals(mobEquipmentPacket.item)) { this.server.getLogger().debug("Tried to equip " + mobEquipmentPacket.item + " but have " + item + " in target slot"); this.inventory.sendContents(this); return; } this.inventory.equipItem(mobEquipmentPacket.hotbarSlot); this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); break; case ProtocolInfo.PLAYER_ACTION_PACKET: PlayerActionPacket playerActionPacket = (PlayerActionPacket) packet; if (!this.spawned || (!this.isAlive() && playerActionPacket.action != PlayerActionPacket.ACTION_RESPAWN && playerActionPacket.action != PlayerActionPacket.ACTION_DIMENSION_CHANGE_REQUEST)) { break; } playerActionPacket.entityId = this.id; Vector3 pos = new Vector3(playerActionPacket.x, playerActionPacket.y, playerActionPacket.z); BlockFace face = BlockFace.fromIndex(playerActionPacket.face); switch (playerActionPacket.action) { case PlayerActionPacket.ACTION_START_BREAK: if (this.lastBreak != Long.MAX_VALUE || pos.distanceSquared(this) > 100) { break; } Block target = this.level.getBlock(pos); PlayerInteractEvent playerInteractEvent = new PlayerInteractEvent(this, this.inventory.getItemInHand(), target, face, target.getId() == 0 ? Action.LEFT_CLICK_AIR : Action.LEFT_CLICK_BLOCK); this.getServer().getPluginManager().callEvent(playerInteractEvent); if (playerInteractEvent.isCancelled()) { this.inventory.sendHeldItem(this); break; } if (target.getId() == Block.NOTEBLOCK) { ((BlockNoteblock) target).emitSound(); break; } Block block = target.getSide(face); if (block.getId() == Block.FIRE) { this.level.setBlock(block, new BlockAir(), true); break; } if (!this.isCreative()) { //improved this to take stuff like swimming, ladders, enchanted tools into account, fix wrong tool break time calculations for bad tools (pmmp/PocketMine-MP#211) //Done by lmlstarqaq double breakTime = Math.ceil(target.getBreakTime(this.inventory.getItemInHand(), this) * 20); if (breakTime > 0) { LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_START_BREAK; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = (int) (65535 / breakTime); this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); } } this.breakingBlock = target; this.lastBreak = System.currentTimeMillis(); break; case PlayerActionPacket.ACTION_ABORT_BREAK: this.lastBreak = Long.MAX_VALUE; this.breakingBlock = null; case PlayerActionPacket.ACTION_STOP_BREAK: LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_STOP_BREAK; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = 0; this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); this.breakingBlock = null; break; case PlayerActionPacket.ACTION_GET_UPDATED_BLOCK: break; //TODO case PlayerActionPacket.ACTION_DROP_ITEM: break; //TODO case PlayerActionPacket.ACTION_STOP_SLEEPING: this.stopSleep(); break; case PlayerActionPacket.ACTION_RESPAWN: if (!this.spawned || this.isAlive() || !this.isOnline()) { break; } if (this.server.isHardcore()) { this.setBanned(true); break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); PlayerRespawnEvent playerRespawnEvent = new PlayerRespawnEvent(this, this.getSpawn()); this.server.getPluginManager().callEvent(playerRespawnEvent); Position respawnPos = playerRespawnEvent.getRespawnPosition(); this.teleport(respawnPos, null); RespawnPacket respawnPacket = new RespawnPacket(); respawnPacket.x = (float) respawnPos.x; respawnPacket.y = (float) respawnPos.y; respawnPacket.z = (float) respawnPos.z; this.dataPacket(respawnPacket); this.setSprinting(false, true); this.setSneaking(false); this.extinguish(); this.setDataProperty(new ShortEntityData(Player.DATA_AIR, 400), false); this.deadTicks = 0; this.noDamageTicks = 60; this.removeAllEffects(); this.setHealth(this.getMaxHealth()); this.getFoodData().setLevel(20, 20); this.sendData(this); this.setMovementSpeed(DEFAULT_SPEED); this.getAdventureSettings().update(); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); this.spawnToAll(); this.scheduleUpdate(); break; case PlayerActionPacket.ACTION_JUMP: break packetswitch; case PlayerActionPacket.ACTION_START_SPRINT: PlayerToggleSprintEvent playerToggleSprintEvent = new PlayerToggleSprintEvent(this, true); this.server.getPluginManager().callEvent(playerToggleSprintEvent); if (playerToggleSprintEvent.isCancelled()) { this.sendData(this); } else { this.setSprinting(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_SPRINT: playerToggleSprintEvent = new PlayerToggleSprintEvent(this, false); this.server.getPluginManager().callEvent(playerToggleSprintEvent); if (playerToggleSprintEvent.isCancelled()) { this.sendData(this); } else { this.setSprinting(false); } break packetswitch; case PlayerActionPacket.ACTION_START_SNEAK: PlayerToggleSneakEvent playerToggleSneakEvent = new PlayerToggleSneakEvent(this, true); this.server.getPluginManager().callEvent(playerToggleSneakEvent); if (playerToggleSneakEvent.isCancelled()) { this.sendData(this); } else { this.setSneaking(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_SNEAK: playerToggleSneakEvent = new PlayerToggleSneakEvent(this, false); this.server.getPluginManager().callEvent(playerToggleSneakEvent); if (playerToggleSneakEvent.isCancelled()) { this.sendData(this); } else { this.setSneaking(false); } break packetswitch; case PlayerActionPacket.ACTION_DIMENSION_CHANGE_ACK: break; //TODO case PlayerActionPacket.ACTION_START_GLIDE: PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, true); this.server.getPluginManager().callEvent(playerToggleGlideEvent); if (playerToggleGlideEvent.isCancelled()) { this.sendData(this); } else { this.setGliding(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_GLIDE: playerToggleGlideEvent = new PlayerToggleGlideEvent(this, false); this.server.getPluginManager().callEvent(playerToggleGlideEvent); if (playerToggleGlideEvent.isCancelled()) { this.sendData(this); } else { this.setGliding(false); } break packetswitch; case PlayerActionPacket.ACTION_CONTINUE_BREAK: if (this.isBreakingBlock()) { block = this.level.getBlock(pos); this.level.addParticle(new PunchBlockParticle(pos, block, face)); } break; } this.startAction = -1; this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); break; case ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET: break; case ProtocolInfo.MODAL_FORM_RESPONSE_PACKET: if (!this.spawned || !this.isAlive()) { break; } ModalFormResponsePacket modalFormPacket = (ModalFormResponsePacket) packet; if (formWindows.containsKey(modalFormPacket.formId)) { FormWindow window = formWindows.remove(modalFormPacket.formId); window.setResponse(modalFormPacket.data.trim()); PlayerFormRespondedEvent event = new PlayerFormRespondedEvent(this, modalFormPacket.formId, window); getServer().getPluginManager().callEvent(event); } else if (serverSettings.containsKey(modalFormPacket.formId)) { FormWindow window = serverSettings.get(modalFormPacket.formId); window.setResponse(modalFormPacket.data.trim()); PlayerSettingsRespondedEvent event = new PlayerSettingsRespondedEvent(this, modalFormPacket.formId, window); getServer().getPluginManager().callEvent(event); //Set back new settings if not been cancelled if (!event.isCancelled() && window instanceof FormWindowCustom) ((FormWindowCustom) window).setElementsFromResponse(); } break; case ProtocolInfo.INTERACT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; //this.resetCraftingGridType(); InteractPacket interactPacket = (InteractPacket) packet; Entity targetEntity = this.level.getEntity(interactPacket.target); if (targetEntity == null || !this.isAlive() || !targetEntity.isAlive()) { break; } if (targetEntity instanceof EntityItem || targetEntity instanceof EntityArrow || targetEntity instanceof EntityXPOrb) { this.kick(PlayerKickEvent.Reason.INVALID_PVE, "Attempting to interact with an invalid entity"); this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidEntity", this.getName())); break; } item = this.inventory.getItemInHand(); switch (interactPacket.action) { case InteractPacket.ACTION_MOUSEOVER: this.getServer().getPluginManager().callEvent(new PlayerMouseOverEntityEvent(this, targetEntity)); break; case InteractPacket.ACTION_VEHICLE_EXIT: if (!(targetEntity instanceof EntityRideable) || this.riding == null) { break; } ((EntityRideable) riding).mountEntity(this); break; } break; case ProtocolInfo.BLOCK_PICK_REQUEST_PACKET: BlockPickRequestPacket pickRequestPacket = (BlockPickRequestPacket) packet; Block block = this.level.getBlock(this.temporalVector.setComponents(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); item = block.toItem(); if (pickRequestPacket.addUserData) { BlockEntity blockEntity = this.getLevel().getBlockEntity(new Vector3(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); if (blockEntity != null) { CompoundTag nbt = blockEntity.getCleanedNBT(); if (nbt != null) { Item item1 = this.getInventory().getItemInHand(); item1.setCustomBlockData(nbt); item1.setLore("+(DATA)"); this.getInventory().setItemInHand(item1); } } } PlayerBlockPickEvent pickEvent = new PlayerBlockPickEvent(this, block, item); if (!this.isCreative()) { this.server.getLogger().debug("Got block-pick request from " + this.getName() + " when not in creative mode (gamemode " + this.getGamemode() + ")"); pickEvent.setCancelled(); } this.server.getPluginManager().callEvent(pickEvent); if (!pickEvent.isCancelled()) { this.inventory.setItemInHand(pickEvent.getItem()); } break; case ProtocolInfo.ANIMATE_PACKET: if (!this.spawned || !this.isAlive()) { break; } PlayerAnimationEvent animationEvent = new PlayerAnimationEvent(this, ((AnimatePacket) packet).action); this.server.getPluginManager().callEvent(animationEvent); if (animationEvent.isCancelled()) { break; } AnimatePacket animatePacket = new AnimatePacket(); animatePacket.eid = this.getId(); animatePacket.action = animationEvent.getAnimationType(); Server.broadcastPacket(this.getViewers().values(), animatePacket); break; case ProtocolInfo.SET_HEALTH_PACKET: //use UpdateAttributePacket instead break; case ProtocolInfo.ENTITY_EVENT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; //this.resetCraftingGridType(); EntityEventPacket entityEventPacket = (EntityEventPacket) packet; switch (entityEventPacket.event) { case EntityEventPacket.EATING_ITEM: if (entityEventPacket.data == 0) { break; } /*this.dataPacket(packet); //bug? Server.broadcastPacket(this.getViewers().values(), packet);*/ break; } break; case ProtocolInfo.COMMAND_REQUEST_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = 0; CommandRequestPacket commandRequestPacket = (CommandRequestPacket) packet; PlayerCommandPreprocessEvent playerCommandPreprocessEvent = new PlayerCommandPreprocessEvent(this, commandRequestPacket.command); this.server.getPluginManager().callEvent(playerCommandPreprocessEvent); if (playerCommandPreprocessEvent.isCancelled()) { break; } Timings.playerCommandTimer.startTiming(); this.server.dispatchCommand(playerCommandPreprocessEvent.getPlayer(), playerCommandPreprocessEvent.getMessage().substring(1)); Timings.playerCommandTimer.stopTiming(); break; case ProtocolInfo.TEXT_PACKET: if (!this.spawned || !this.isAlive()) { break; } TextPacket textPacket = (TextPacket) packet; if (textPacket.type == TextPacket.TYPE_CHAT) { this.chat(textPacket.message); } break; case ProtocolInfo.CONTAINER_CLOSE_PACKET: ContainerClosePacket containerClosePacket = (ContainerClosePacket) packet; if (!this.spawned || containerClosePacket.windowId == 0) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); if (this.windowIndex.containsKey(containerClosePacket.windowId)) { this.server.getPluginManager().callEvent(new InventoryCloseEvent(this.windowIndex.get(containerClosePacket.windowId), this)); this.removeWindow(this.windowIndex.get(containerClosePacket.windowId)); } else { this.windowIndex.remove(containerClosePacket.windowId); } break; case ProtocolInfo.CRAFTING_EVENT_PACKET: break; case ProtocolInfo.BLOCK_ENTITY_DATA_PACKET: if (!this.spawned || !this.isAlive()) { break; } BlockEntityDataPacket blockEntityDataPacket = (BlockEntityDataPacket) packet; this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); pos = new Vector3(blockEntityDataPacket.x, blockEntityDataPacket.y, blockEntityDataPacket.z); if (pos.distanceSquared(this) > 10000) { break; } BlockEntity t = this.level.getBlockEntity(pos); if (t instanceof BlockEntitySpawnable) { CompoundTag nbt; try { nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); } catch (IOException e) { throw new RuntimeException(e); } if (!((BlockEntitySpawnable) t).updateCompoundTag(nbt, this)) { ((BlockEntitySpawnable) t).spawnTo(this); } } break; case ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET: RequestChunkRadiusPacket requestChunkRadiusPacket = (RequestChunkRadiusPacket) packet; ChunkRadiusUpdatedPacket chunkRadiusUpdatePacket = new ChunkRadiusUpdatedPacket(); this.chunkRadius = Math.max(3, Math.min(requestChunkRadiusPacket.radius, this.viewDistance)); chunkRadiusUpdatePacket.radius = this.chunkRadius; this.dataPacket(chunkRadiusUpdatePacket); break; case ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET: SetPlayerGameTypePacket setPlayerGameTypePacket = (SetPlayerGameTypePacket) packet; if (setPlayerGameTypePacket.gamemode != this.gamemode) { if (!this.hasPermission("nukkit.command.gamemode")) { SetPlayerGameTypePacket setPlayerGameTypePacket1 = new SetPlayerGameTypePacket(); setPlayerGameTypePacket1.gamemode = this.gamemode & 0x01; this.dataPacket(setPlayerGameTypePacket1); this.getAdventureSettings().update(); break; } this.setGamemode(setPlayerGameTypePacket.gamemode, true); Command.broadcastCommandMessage(this, new TranslationContainer("commands.gamemode.success.self", Server.getGamemodeString(this.gamemode))); } break; case ProtocolInfo.ITEM_FRAME_DROP_ITEM_PACKET: ItemFrameDropItemPacket itemFrameDropItemPacket = (ItemFrameDropItemPacket) packet; Vector3 vector3 = this.temporalVector.setComponents(itemFrameDropItemPacket.x, itemFrameDropItemPacket.y, itemFrameDropItemPacket.z); BlockEntity blockEntityItemFrame = this.level.getBlockEntity(vector3); BlockEntityItemFrame itemFrame = (BlockEntityItemFrame) blockEntityItemFrame; if (itemFrame != null) { block = itemFrame.getBlock(); Item itemDrop = itemFrame.getItem(); ItemFrameDropItemEvent itemFrameDropItemEvent = new ItemFrameDropItemEvent(this, block, itemFrame, itemDrop); this.server.getPluginManager().callEvent(itemFrameDropItemEvent); if (!itemFrameDropItemEvent.isCancelled()) { if (itemDrop.getId() != Item.AIR) { vector3 = this.temporalVector.setComponents(itemFrame.x + 0.5, itemFrame.y, itemFrame.z + 0.5); this.level.dropItem(vector3, itemDrop); itemFrame.setItem(new ItemBlock(new BlockAir())); itemFrame.setItemRotation(0); this.getLevel().addSound(this, Sound.BLOCK_ITEMFRAME_REMOVE_ITEM); } } else { itemFrame.spawnTo(this); } } break; case ProtocolInfo.MAP_INFO_REQUEST_PACKET: MapInfoRequestPacket pk = (MapInfoRequestPacket) packet; Item mapItem = null; for (Item item1 : this.inventory.getContents().values()) { if (item1 instanceof ItemMap && ((ItemMap) item1).getMapId() == pk.mapId) { mapItem = item1; } } if (mapItem == null) { for (BlockEntity be : this.level.getBlockEntities().values()) { if (be instanceof BlockEntityItemFrame) { BlockEntityItemFrame itemFrame1 = (BlockEntityItemFrame) be; if (itemFrame1.getItem() instanceof ItemMap && ((ItemMap) itemFrame1.getItem()).getMapId() == pk.mapId) { ((ItemMap) itemFrame1.getItem()).sendImage(this); break; } } } } if (mapItem != null) { PlayerMapInfoRequestEvent event; getServer().getPluginManager().callEvent(event = new PlayerMapInfoRequestEvent(this, mapItem)); if (!event.isCancelled()) { ((ItemMap) mapItem).sendImage(this); } } break; case ProtocolInfo.LEVEL_SOUND_EVENT_PACKET: //LevelSoundEventPacket levelSoundEventPacket = (LevelSoundEventPacket) packet; //We just need to broadcast this packet to all viewers. this.level.addChunkPacket(this.getFloorX() >> 4, this.getFloorZ() >> 4, packet); break; case ProtocolInfo.INVENTORY_TRANSACTION_PACKET: if (this.isSpectator()) { this.sendAllInventories(); break; } InventoryTransactionPacket transactionPacket = (InventoryTransactionPacket) packet; List<InventoryAction> actions = new ArrayList<>(); for (NetworkInventoryAction networkInventoryAction : transactionPacket.actions) { InventoryAction a = networkInventoryAction.createInventoryAction(this); if (a == null) { this.getServer().getLogger().debug("Unmatched inventory action from " + this.getName() + ": " + networkInventoryAction); this.sendAllInventories(); break packetswitch; } actions.add(a); } if (transactionPacket.isCraftingPart) { if (this.craftingTransaction == null) { this.craftingTransaction = new CraftingTransaction(this, actions); } else { for (InventoryAction action : actions) { this.craftingTransaction.addAction(action); } } if (this.craftingTransaction.getPrimaryOutput() != null) { //we get the actions for this in several packets, so we can't execute it until we get the result this.craftingTransaction.execute(); this.craftingTransaction = null; } return; } else if (this.craftingTransaction != null) { this.server.getLogger().debug("Got unexpected normal inventory action with incomplete crafting transaction from " + this.getName() + ", refusing to execute crafting"); this.craftingTransaction = null; } switch (transactionPacket.transactionType) { case InventoryTransactionPacket.TYPE_NORMAL: InventoryTransaction transaction = new InventoryTransaction(this, actions); if (!transaction.execute()) { this.server.getLogger().debug("Failed to execute inventory transaction from " + this.getName() + " with actions: " + Arrays.toString(transactionPacket.actions)); break packetswitch; //oops! } //TODO: fix achievement for getting iron from furnace break packetswitch; case InventoryTransactionPacket.TYPE_MISMATCH: if (transactionPacket.actions.length > 0) { this.server.getLogger().debug("Expected 0 actions for mismatch, got " + transactionPacket.actions.length + ", " + Arrays.toString(transactionPacket.actions)); } this.sendAllInventories(); break packetswitch; case InventoryTransactionPacket.TYPE_USE_ITEM: UseItemData useItemData = (UseItemData) transactionPacket.transactionData; BlockVector3 blockVector = useItemData.blockPos; face = useItemData.face; int type = useItemData.actionType; switch (type) { case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_BLOCK: this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 13 : 7)) { if (this.isCreative()) { Item i = inventory.getItemInHand(); if (this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this) != null) { break packetswitch; } } else if (inventory.getItemInHand().equals(useItemData.itemInHand)) { Item i = inventory.getItemInHand(); Item oldItem = i.clone(); //TODO: Implement adventure mode checks if ((i = this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this)) != null) { if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { inventory.setItemInHand(i); inventory.sendHeldItem(this.getViewers().values()); } break packetswitch; } } } inventory.sendHeldItem(this); if (blockVector.distanceSquared(this) > 10000) { break packetswitch; } Block target = this.level.getBlock(blockVector.asVector3()); block = target.getSide(face); this.level.sendBlocks(new Player[]{this}, new Block[]{target, block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); if (target instanceof BlockDoor) { BlockDoor door = (BlockDoor) target; Block part; if ((door.getDamage() & 0x08) > 0) { //up part = target.down(); if (part.getId() == target.getId()) { target = part; this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); } } } break packetswitch; case InventoryTransactionPacket.USE_ITEM_ACTION_BREAK_BLOCK: if (!this.spawned || !this.isAlive()) { break packetswitch; } this.resetCraftingGridType(); Item i = this.getInventory().getItemInHand(); Item oldItem = i.clone(); if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 13 : 7) && (i = this.level.useBreakOn(blockVector.asVector3(), i, this, true)) != null) { if (this.isSurvival()) { this.getFoodData().updateFoodExpLevel(0.025); if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { inventory.setItemInHand(i); inventory.sendHeldItem(this.getViewers().values()); } } break packetswitch; } inventory.sendContents(this); target = this.level.getBlock(blockVector.asVector3()); BlockEntity blockEntity = this.level.getBlockEntity(blockVector.asVector3()); this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); inventory.sendHeldItem(this); if (blockEntity instanceof BlockEntitySpawnable) { ((BlockEntitySpawnable) blockEntity).spawnTo(this); } break packetswitch; case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_AIR: Vector3 directionVector = this.getDirectionVector(); if (this.isCreative()) { item = this.inventory.getItemInHand(); } else if (!this.inventory.getItemInHand().equals(useItemData.itemInHand)) { this.inventory.sendHeldItem(this); break packetswitch; } else { item = this.inventory.getItemInHand(); } PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, item, directionVector, face, Action.RIGHT_CLICK_AIR); this.server.getPluginManager().callEvent(interactEvent); if (interactEvent.isCancelled()) { this.inventory.sendHeldItem(this); break packetswitch; } if (item.onClickAir(this, directionVector) && this.isSurvival()) { this.inventory.setItemInHand(item); } this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, true); this.startAction = this.server.getTick(); break packetswitch; default: //unknown break; } break; case InventoryTransactionPacket.TYPE_USE_ITEM_ON_ENTITY: UseItemOnEntityData useItemOnEntityData = (UseItemOnEntityData) transactionPacket.transactionData; Entity target = this.level.getEntity(useItemOnEntityData.entityRuntimeId); if (target == null) { return; } type = useItemOnEntityData.actionType; if (!useItemOnEntityData.itemInHand.equalsExact(this.inventory.getItemInHand())) { this.inventory.sendHeldItem(this); } item = this.inventory.getItemInHand(); switch (type) { case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_INTERACT: PlayerInteractEntityEvent playerInteractEntityEvent = new PlayerInteractEntityEvent(this, target, item); if (this.isSpectator()) playerInteractEntityEvent.setCancelled(); getServer().getPluginManager().callEvent(playerInteractEntityEvent); if (playerInteractEntityEvent.isCancelled()) { break; } if (target.onInteract(this, item) && this.isSurvival()) { if (item.isTool()) { if (item.useOn(target) && item.getDamage() >= item.getMaxDurability()) { item = new ItemBlock(new BlockAir()); } } else { if (item.count > 1) { item.count--; } else { item = new ItemBlock(new BlockAir()); } } this.inventory.setItemInHand(item); } break; case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_ATTACK: float itemDamage = item.getAttackDamage(); for (Enchantment enchantment : item.getEnchantments()) { itemDamage += enchantment.getDamageBonus(target); } Map<DamageModifier, Float> damage = new EnumMap<>(DamageModifier.class); damage.put(DamageModifier.BASE, itemDamage); if (!this.canInteract(target, isCreative() ? 8 : 5)) { break; } else if (target instanceof Player) { if ((((Player) target).getGamemode() & 0x01) > 0) { break; } else if (!this.server.getPropertyBoolean("pvp") || this.server.getDifficulty() == 0) { break; } } EntityDamageByEntityEvent entityDamageByEntityEvent = new EntityDamageByEntityEvent(this, target, DamageCause.ENTITY_ATTACK, damage); if (this.isSpectator()) entityDamageByEntityEvent.setCancelled(); if ((target instanceof Player) && !this.level.getGameRules().getBoolean(GameRule.PVP)) { entityDamageByEntityEvent.setCancelled(); } if (!target.attack(entityDamageByEntityEvent)) { if (item.isTool() && this.isSurvival()) { this.inventory.sendContents(this); } break; } for (Enchantment enchantment : item.getEnchantments()) { enchantment.doPostAttack(this, target); } if (item.isTool() && this.isSurvival()) { if (item.useOn(target) && item.getDamage() >= item.getMaxDurability()) { this.inventory.setItemInHand(new ItemBlock(new BlockAir())); } else { this.inventory.setItemInHand(item); } } return; default: break; //unknown } break; case InventoryTransactionPacket.TYPE_RELEASE_ITEM: if (this.isSpectator()) { this.sendAllInventories(); break packetswitch; } ReleaseItemData releaseItemData = (ReleaseItemData) transactionPacket.transactionData; try { type = releaseItemData.actionType; switch (type) { case InventoryTransactionPacket.RELEASE_ITEM_ACTION_RELEASE: if (this.isUsingItem()) { item = this.inventory.getItemInHand(); if (item.onReleaseUsing(this)) { this.inventory.setItemInHand(item); } } else { this.inventory.sendContents(this); } return; case InventoryTransactionPacket.RELEASE_ITEM_ACTION_CONSUME: Item itemInHand = this.inventory.getItemInHand(); PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(this, itemInHand); if (itemInHand.getId() == Item.POTION) { this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } Potion potion = Potion.getPotion(itemInHand.getDamage()).setSplash(false); if (this.getGamemode() == SURVIVAL) { --itemInHand.count; this.inventory.setItemInHand(itemInHand); this.inventory.addItem(new ItemGlassBottle()); } if (potion != null) { potion.applyPotion(this); } } else if (itemInHand.getId() == Item.BUCKET && itemInHand.getDamage() == 1) { //milk this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } EntityEventPacket eventPacket = new EntityEventPacket(); eventPacket.eid = this.getId(); eventPacket.event = EntityEventPacket.USE_ITEM; this.dataPacket(eventPacket); Server.broadcastPacket(this.getViewers().values(), eventPacket); if (this.isSurvival()) { itemInHand.count--; this.inventory.setItemInHand(itemInHand); this.inventory.addItem(new ItemBucket()); } this.removeAllEffects(); } else { this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } Food food = Food.getByRelative(itemInHand); if (food != null && food.eatenBy(this)) --itemInHand.count; this.inventory.setItemInHand(itemInHand); } return; default: break; } } finally { this.setUsingItem(false); } break; default: this.inventory.sendContents(this); break; } break; case ProtocolInfo.PLAYER_HOTBAR_PACKET: PlayerHotbarPacket hotbarPacket = (PlayerHotbarPacket) packet; if (hotbarPacket.windowId != ContainerIds.INVENTORY) { return; //In PE this should never happen } this.inventory.equipItem(hotbarPacket.selectedHotbarSlot); break; case ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET: PlayerServerSettingsRequestEvent settingsRequestEvent = new PlayerServerSettingsRequestEvent(this, new HashMap<>(this.serverSettings)); this.getServer().getPluginManager().callEvent(settingsRequestEvent); if (!settingsRequestEvent.isCancelled()) { settingsRequestEvent.getSettings().forEach((id, window) -> { ServerSettingsResponsePacket re = new ServerSettingsResponsePacket(); re.formId = id; re.data = window.getJSONData(); this.dataPacket(re); }); } break; default: break; } } } /** * Sends a chat message as this player. If the message begins with a / (forward-slash) it will be treated * as a command. */ public boolean chat(String message) { if (!this.spawned || !this.isAlive()) { return false; } this.resetCraftingGridType(); this.craftingType = CRAFTING_SMALL; if (this.removeFormat) { message = TextFormat.clean(message); } for (String msg : message.split("\n")) { if (!msg.trim().isEmpty() && msg.length() <= 255 && this.messageCounter-- > 0) { PlayerChatEvent chatEvent = new PlayerChatEvent(this, msg); this.server.getPluginManager().callEvent(chatEvent); if (!chatEvent.isCancelled()) { this.server.broadcastMessage(this.getServer().getLanguage().translateString(chatEvent.getFormat(), new String[]{chatEvent.getPlayer().getDisplayName(), chatEvent.getMessage()}), chatEvent.getRecipients()); } } } return true; } public boolean kick() { return this.kick(""); } public boolean kick(String reason, boolean isAdmin) { return this.kick(PlayerKickEvent.Reason.UNKNOWN, reason, isAdmin); } public boolean kick(String reason) { return kick(PlayerKickEvent.Reason.UNKNOWN, reason); } public boolean kick(PlayerKickEvent.Reason reason) { return this.kick(reason, true); } public boolean kick(PlayerKickEvent.Reason reason, String reasonString) { return this.kick(reason, reasonString, true); } public boolean kick(PlayerKickEvent.Reason reason, boolean isAdmin) { return this.kick(reason, reason.toString(), isAdmin); } public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean isAdmin) { PlayerKickEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerKickEvent(this, reason, this.getLeaveMessage())); if (!ev.isCancelled()) { String message; if (isAdmin) { if (!this.isBanned()) { message = "Kicked by admin." + (!reasonString.isEmpty() ? " Reason: " + reasonString : ""); } else { message = reasonString; } } else { if (reasonString.isEmpty()) { message = "disconnectionScreen.noReason"; } else { message = reasonString; } } this.close(ev.getQuitMessage(), message); return true; } return false; } public void setViewDistance(int distance) { this.chunkRadius = distance; ChunkRadiusUpdatedPacket pk = new ChunkRadiusUpdatedPacket(); pk.radius = distance; this.dataPacket(pk); } public int getViewDistance() { return this.chunkRadius; } @Override public void sendMessage(String message) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message); this.dataPacket(pk); } @Override public void sendMessage(TextContainer message) { if (message instanceof TranslationContainer) { this.sendTranslation(message.getText(), ((TranslationContainer) message).getParameters()); return; } this.sendMessage(message.getText()); } public void sendTranslation(String message) { this.sendTranslation(message, new String[0]); } public void sendTranslation(String message, String[] parameters) { TextPacket pk = new TextPacket(); if (!this.server.isLanguageForced()) { pk.type = TextPacket.TYPE_TRANSLATION; pk.message = this.server.getLanguage().translateString(message, parameters, "nukkit."); for (int i = 0; i < parameters.length; i++) { parameters[i] = this.server.getLanguage().translateString(parameters[i], parameters, "nukkit."); } pk.parameters = parameters; } else { pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message, parameters); } this.dataPacket(pk); } public void sendChat(String message) { this.sendChat("", message); } public void sendChat(String source, String message) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_CHAT; pk.source = source; pk.message = this.server.getLanguage().translateString(message); this.dataPacket(pk); } public void sendPopup(String message) { this.sendPopup(message, ""); } public void sendPopup(String message, String subtitle) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_POPUP; pk.source = message; pk.message = subtitle; this.dataPacket(pk); } public void sendTip(String message) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_TIP; pk.message = message; this.dataPacket(pk); } public void clearTitle() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_CLEAR; this.dataPacket(pk); } /** * Resets both title animation times and subtitle for the next shown title */ public void resetTitleSettings() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_RESET; this.dataPacket(pk); } public void setSubtitle(String subtitle) { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_SUBTITLE; pk.text = subtitle; this.dataPacket(pk); } public void setTitleAnimationTimes(int fadein, int duration, int fadeout) { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_ANIMATION_TIMES; pk.fadeInTime = fadein; pk.stayTime = duration; pk.fadeOutTime = fadeout; this.dataPacket(pk); } public void sendTitle(String title) { this.sendTitle(title, "", 20, 20, 5); } public void sendTitle(String title, String subtitle) { this.sendTitle(title, subtitle, 20, 20, 5); } public void sendTitle(String title, String subtitle, int fadein, int duration, int fadeout) { if (!subtitle.equals("")) { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_SUBTITLE; pk.text = subtitle; pk.fadeInTime = fadein; pk.stayTime = duration; pk.fadeOutTime = fadeout; this.dataPacket(pk); } SetTitlePacket pk2 = new SetTitlePacket(); pk2.type = SetTitlePacket.TYPE_TITLE; pk2.text = title; pk2.fadeInTime = fadein; pk2.stayTime = duration; pk2.fadeOutTime = fadeout; this.dataPacket(pk2); } public void sendActionBar(String title) { this.sendActionBar(title, 1, 0, 1); } public void sendActionBar(String title, int fadein, int duration, int fadeout) { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_ACTION_BAR; pk.text = title; pk.fadeInTime = fadein; pk.stayTime = duration; pk.fadeOutTime = fadeout; this.dataPacket(pk); } @Override public void close() { this.close(""); } public void close(String message) { this.close(message, "generic"); } public void close(String message, String reason) { this.close(message, reason, true); } public void close(String message, String reason, boolean notify) { this.close(new TextContainer(message), reason, notify); } public void close(TextContainer message) { this.close(message, "generic"); } public void close(TextContainer message, String reason) { this.close(message, reason, true); } public void close(TextContainer message, String reason, boolean notify) { if (this.connected && !this.closed) { if (notify && reason.length() > 0) { DisconnectPacket pk = new DisconnectPacket(); pk.message = reason; this.directDataPacket(pk); } this.connected = false; PlayerQuitEvent ev = null; if (this.getName() != null && this.getName().length() > 0) { this.server.getPluginManager().callEvent(ev = new PlayerQuitEvent(this, message, true, reason)); if (this.loggedIn && ev.getAutoSave()) { this.save(); } } for (Player player : new ArrayList<>(this.server.getOnlinePlayers().values())) { if (!player.canSee(this)) { player.showPlayer(this); } } this.hiddenPlayers.clear(); this.removeAllWindows(true); for (long index : new ArrayList<>(this.usedChunks.keySet())) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); this.level.unregisterChunkLoader(this, chunkX, chunkZ); this.usedChunks.remove(index); } super.close(); this.interfaz.close(this, notify ? reason : ""); if (this.loggedIn) { this.server.removeOnlinePlayer(this); } this.loggedIn = false; if (ev != null && !Objects.equals(this.username, "") && this.spawned && !Objects.equals(ev.getQuitMessage().toString(), "")) { this.server.broadcastMessage(ev.getQuitMessage()); } this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.spawned = false; this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logOut", TextFormat.AQUA + (this.getName() == null ? "" : this.getName()) + TextFormat.WHITE, this.ip, String.valueOf(this.port), this.getServer().getLanguage().translateString(reason))); this.windows = new HashMap<>(); this.windowIndex.clear(); this.usedChunks.clear(); this.loadQueue.clear(); this.hasSpawned.clear(); this.spawnPosition = null; if (this.riding instanceof EntityRideable) { this.riding.linkedEntity = null; } this.riding = null; } if (this.perm != null) { this.perm.clearPermissions(); this.perm = null; } if (this.inventory != null) { this.inventory = null; } this.chunk = null; this.server.removePlayer(this); } public void save() { this.save(false); } public void save(boolean async) { if (this.closed) { throw new IllegalStateException("Tried to save closed player"); } super.saveNBT(); if (this.level != null) { this.namedTag.putString("Level", this.level.getFolderName()); if (this.spawnPosition != null && this.spawnPosition.getLevel() != null) { this.namedTag.putString("SpawnLevel", this.spawnPosition.getLevel().getFolderName()); this.namedTag.putInt("SpawnX", (int) this.spawnPosition.x); this.namedTag.putInt("SpawnY", (int) this.spawnPosition.y); this.namedTag.putInt("SpawnZ", (int) this.spawnPosition.z); } CompoundTag achievements = new CompoundTag(); for (String achievement : this.achievements) { achievements.putByte(achievement, 1); } this.namedTag.putCompound("Achievements", achievements); this.namedTag.putInt("playerGameType", this.gamemode); this.namedTag.putLong("lastPlayed", System.currentTimeMillis() / 1000); this.namedTag.putString("lastIP", this.getAddress()); this.namedTag.putInt("EXP", this.getExperience()); this.namedTag.putInt("expLevel", this.getExperienceLevel()); this.namedTag.putInt("foodLevel", this.getFoodData().getLevel()); this.namedTag.putFloat("foodSaturationLevel", this.getFoodData().getFoodSaturationLevel()); if (!this.username.isEmpty() && this.namedTag != null) { this.server.saveOfflinePlayerData(this.username, this.namedTag, async); } } } public String getName() { return this.username; } @Override public void kill() { if (!this.spawned) { return; } boolean showMessages = this.level.getGameRules().getBoolean(GameRule.SHOW_DEATH_MESSAGE); String message = "death.attack.generic"; List<String> params = new ArrayList<>(); params.add(this.getDisplayName()); if (showMessages) { EntityDamageEvent cause = this.getLastDamageCause(); switch (cause == null ? DamageCause.CUSTOM : cause.getCause()) { case ENTITY_ATTACK: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.player"; params.add(((Player) e).getDisplayName()); break; } else if (e instanceof EntityLiving) { message = "death.attack.mob"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { params.add("Unknown"); } } break; case PROJECTILE: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.arrow"; params.add(((Player) e).getDisplayName()); } else if (e instanceof EntityLiving) { message = "death.attack.arrow"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { params.add("Unknown"); } } break; case SUICIDE: message = "death.attack.generic"; break; case VOID: message = "death.attack.outOfWorld"; break; case FALL: if (cause != null) { if (cause.getFinalDamage() > 2) { message = "death.fell.accident.generic"; break; } } message = "death.attack.fall"; break; case SUFFOCATION: message = "death.attack.inWall"; break; case LAVA: message = "death.attack.lava"; break; case FIRE: message = "death.attack.onFire"; break; case FIRE_TICK: message = "death.attack.inFire"; break; case DROWNING: message = "death.attack.drown"; break; case CONTACT: if (cause instanceof EntityDamageByBlockEvent) { if (((EntityDamageByBlockEvent) cause).getDamager().getId() == Block.CACTUS) { message = "death.attack.cactus"; } } break; case BLOCK_EXPLOSION: case ENTITY_EXPLOSION: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.explosion.player"; params.add(((Player) e).getDisplayName()); } else if (e instanceof EntityLiving) { message = "death.attack.explosion.player"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } } else { message = "death.attack.explosion"; } break; case MAGIC: message = "death.attack.magic"; break; case CUSTOM: break; default: break; } } else { message = ""; params.clear(); } this.health = 0; this.scheduleUpdate(); PlayerDeathEvent ev = new PlayerDeathEvent(this, this.getDrops(), new TranslationContainer(message, params.stream().toArray(String[]::new)), this.getExperienceLevel()); ev.setKeepExperience(this.level.gameRules.getBoolean(GameRule.KEEP_INVENTORY)); ev.setKeepInventory(ev.getKeepExperience()); this.server.getPluginManager().callEvent(ev); if (!ev.getKeepInventory() && this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { for (Item item : ev.getDrops()) { this.level.dropItem(this, item, null, true, 40); } if (this.inventory != null) { this.inventory.clearAll(); } } if (!ev.getKeepExperience() && this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { if (this.isSurvival() || this.isAdventure()) { int exp = ev.getExperience() * 7; if (exp > 100) exp = 100; int add = 1; for (int ii = 1; ii < exp; ii += add) { this.getLevel().dropExpOrb(this, add); add = new NukkitRandom().nextRange(1, 3); } } this.setExperience(0, 0); } if (showMessages && !ev.getDeathMessage().toString().isEmpty()) { this.server.broadcast(ev.getDeathMessage(), Server.BROADCAST_CHANNEL_USERS); } RespawnPacket pk = new RespawnPacket(); Position pos = this.getSpawn(); pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; this.dataPacket(pk); } @Override public void setHealth(float health) { if (health < 1) { health = 0; } super.setHealth(health); //TODO: Remove it in future! This a hack to solve the client-side absorption bug! WFT Mojang (Half a yellow heart cannot be shown, we can test it in local gaming) Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getAbsorption() % 2 != 0 ? this.getMaxHealth() + 1 : this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0); if (this.spawned) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attr}; pk.entityId = this.id; this.dataPacket(pk); } } @Override public void setMaxHealth(int maxHealth) { super.setMaxHealth(maxHealth); Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getAbsorption() % 2 != 0 ? this.getMaxHealth() + 1 : this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0); if (this.spawned) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attr}; pk.entityId = this.id; this.dataPacket(pk); } } public int getExperience() { return this.exp; } public int getExperienceLevel() { return this.expLevel; } public void addExperience(int add) { if (add == 0) return; int now = this.getExperience(); int added = now + add; int level = this.getExperienceLevel(); int most = calculateRequireExperience(level); while (added >= most) { //Level Up! added = added - most; level++; most = calculateRequireExperience(level); } this.setExperience(added, level); } public static int calculateRequireExperience(int level) { if (level >= 30) { return 112 + (level - 30) * 9; } else if (level >= 15) { return 37 + (level - 15) * 5; } else { return 7 + level * 2; } } public void setExperience(int exp) { setExperience(exp, this.getExperienceLevel()); } //todo something on performance, lots of exp orbs then lots of packets, could crash client public void setExperience(int exp, int level) { this.exp = exp; this.expLevel = level; this.sendExperienceLevel(level); this.sendExperience(exp); } public void sendExperience() { sendExperience(this.getExperience()); } public void sendExperience(int exp) { if (this.spawned) { float percent = ((float) exp) / calculateRequireExperience(this.getExperienceLevel()); this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE).setValue(percent)); } } public void sendExperienceLevel() { sendExperienceLevel(this.getExperienceLevel()); } public void sendExperienceLevel(int level) { if (this.spawned) { this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(level)); } } public void setAttribute(Attribute attribute) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attribute}; pk.entityId = this.id; this.dataPacket(pk); } @Override public void setMovementSpeed(float speed) { super.setMovementSpeed(speed); if (this.spawned) { Attribute attribute = Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(speed); this.setAttribute(attribute); } } public Entity getKiller() { return killer; } @Override public boolean attack(EntityDamageEvent source) { if (!this.isAlive()) { return false; } if (this.isCreative() && source.getCause() != DamageCause.MAGIC && source.getCause() != DamageCause.SUICIDE && source.getCause() != DamageCause.VOID ) { //source.setCancelled(); return false; } else if (this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && source.getCause() == DamageCause.FALL) { //source.setCancelled(); return false; } else if (source.getCause() == DamageCause.FALL) { if (this.getLevel().getBlock(this.getPosition().floor().add(0.5, -1, 0.5)).getId() == Block.SLIME_BLOCK) { if (!this.isSneaking()) { //source.setCancelled(); this.resetFallDistance(); return false; } } } if (source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); if (damager instanceof Player) { ((Player) damager).getFoodData().updateFoodExpLevel(0.3); } //Critical hit boolean add = false; if (!damager.onGround) { NukkitRandom random = new NukkitRandom(); for (int i = 0; i < 5; i++) { CriticalParticle par = new CriticalParticle(new Vector3(this.x + random.nextRange(-15, 15) / 10, this.y + random.nextRange(0, 20) / 10, this.z + random.nextRange(-15, 15) / 10)); this.getLevel().addParticle(par); } add = true; } if (add) source.setDamage((float) (source.getDamage() * 1.5)); } if (super.attack(source)) { //!source.isCancelled() if (this.getLastDamageCause() == source && this.spawned) { this.getFoodData().updateFoodExpLevel(0.3); EntityEventPacket pk = new EntityEventPacket(); pk.eid = this.id; pk.event = EntityEventPacket.HURT_ANIMATION; this.dataPacket(pk); } return true; } else { return false; } } /** * Drops an item on the ground in front of the player. Returns if the item drop was successful. * * @return bool if the item was dropped or if the item was null */ public boolean dropItem(Item item) { if (!this.spawned || !this.isAlive()) { return false; } if (item.isNull()) { this.server.getLogger().debug(this.getName() + " attempted to drop a null item (" + item + ")"); return true; } Vector3 motion = this.getDirectionVector().multiply(0.4); this.level.dropItem(this.add(0, 1.3, 0), item, motion, 40); this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); return true; } public void sendPosition(Vector3 pos) { this.sendPosition(pos, this.yaw); } public void sendPosition(Vector3 pos, double yaw) { this.sendPosition(pos, yaw, this.pitch); } public void sendPosition(Vector3 pos, double yaw, double pitch) { this.sendPosition(pos, yaw, pitch, MovePlayerPacket.MODE_NORMAL); } public void sendPosition(Vector3 pos, double yaw, double pitch, int mode) { this.sendPosition(pos, yaw, pitch, mode, null); } public void sendPosition(Vector3 pos, double yaw, double pitch, int mode, Player[] targets) { MovePlayerPacket pk = new MovePlayerPacket(); pk.eid = this.getId(); pk.x = (float) pos.x; pk.y = (float) (pos.y + this.getEyeHeight()); pk.z = (float) pos.z; pk.headYaw = (float) yaw; pk.pitch = (float) pitch; pk.yaw = (float) yaw; pk.mode = mode; if (targets != null) { Server.broadcastPacket(targets, pk); } else { pk.eid = this.id; this.dataPacket(pk); } } @Override protected void checkChunks() { if (this.chunk == null || (this.chunk.getX() != ((int) this.x >> 4) || this.chunk.getZ() != ((int) this.z >> 4))) { if (this.chunk != null) { this.chunk.removeEntity(this); } this.chunk = this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true); if (!this.justCreated) { Map<Integer, Player> newChunk = this.level.getChunkPlayers((int) this.x >> 4, (int) this.z >> 4); newChunk.remove(this.getLoaderId()); //List<Player> reload = new ArrayList<>(); for (Player player : new ArrayList<>(this.hasSpawned.values())) { if (!newChunk.containsKey(player.getLoaderId())) { this.despawnFrom(player); } else { newChunk.remove(player.getLoaderId()); //reload.add(player); } } for (Player player : newChunk.values()) { this.spawnTo(player); } } if (this.chunk == null) { return; } this.chunk.addEntity(this); } } protected boolean checkTeleportPosition() { if (this.teleportPosition != null) { int chunkX = (int) this.teleportPosition.x >> 4; int chunkZ = (int) this.teleportPosition.z >> 4; for (int X = -1; X <= 1; ++X) { for (int Z = -1; Z <= 1; ++Z) { long index = Level.chunkHash(chunkX + X, chunkZ + Z); if (!this.usedChunks.containsKey(index) || !this.usedChunks.get(index)) { return false; } } } this.spawnToAll(); this.forceMovement = this.teleportPosition; this.teleportPosition = null; return true; } return false; } protected void sendPlayStatus(int status) { sendPlayStatus(status, false); } protected void sendPlayStatus(int status, boolean immediate) { PlayStatusPacket pk = new PlayStatusPacket(); pk.status = status; if (immediate) { this.directDataPacket(pk); } else { this.dataPacket(pk); } } @Override public boolean teleport(Location location, TeleportCause cause) { if (!this.isOnline()) { return false; } Location from = this.getLocation(); Location to = location; if (cause != null) { PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) return false; to = event.getTo(); if (from.getLevel().getId() != to.getLevel().getId()) { //Different level, update compass position SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; Position spawn = to.getLevel().getSpawnLocation(); pk.x = spawn.getFloorX(); pk.y = spawn.getFloorY(); pk.z = spawn.getFloorZ(); dataPacket(pk); } } //TODO Remove it! A hack to solve the client-side teleporting bug! (inside into the block) if (super.teleport(to.getY() == to.getFloorY() ? to.add(0, 0.00001, 0) : to, null)) { // null to prevent fire of duplicate EntityTeleportEvent this.removeAllWindows(); this.teleportPosition = new Vector3(this.x, this.y, this.z); this.forceMovement = this.teleportPosition; this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_TELEPORT); this.checkTeleportPosition(); this.resetFallDistance(); this.nextChunkOrderRun = 0; this.newPosition = null; //DummyBossBar this.getDummyBossBars().values().forEach(DummyBossBar::reshow); //Weather this.getLevel().sendWeather(this); //Update time this.getLevel().sendTime(this); return true; } return false; } protected void forceSendEmptyChunks() { int chunkPositionX = this.getFloorX() >> 4; int chunkPositionZ = this.getFloorZ() >> 4; for (int x = -3; x < 3; x++) { for (int z = -3; z < 3; z++) { FullChunkDataPacket chunk = new FullChunkDataPacket(); chunk.chunkX = chunkPositionX + x; chunk.chunkZ = chunkPositionZ + z; chunk.data = new byte[0]; this.dataPacket(chunk); } } } public void teleportImmediate(Location location) { this.teleportImmediate(location, TeleportCause.PLUGIN); } public void teleportImmediate(Location location, TeleportCause cause) { Location from = this.getLocation(); if (super.teleport(location, cause)) { for (Inventory window : new ArrayList<>(this.windowIndex.values())) { if (window == this.inventory) { continue; } this.removeWindow(window); } if (from.getLevel().getId() != location.getLevel().getId()) { //Different level, update compass position SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; Position spawn = location.getLevel().getSpawnLocation(); pk.x = spawn.getFloorX(); pk.y = spawn.getFloorY(); pk.z = spawn.getFloorZ(); dataPacket(pk); } this.forceMovement = new Vector3(this.x, this.y, this.z); this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); this.resetFallDistance(); this.orderChunks(); this.nextChunkOrderRun = 0; this.newPosition = null; //Weather this.getLevel().sendWeather(this); //Update time this.getLevel().sendTime(this); } } /** * Shows a new FormWindow to the player * You can find out FormWindow result by listening to PlayerFormRespondedEvent */ public int showFormWindow(FormWindow window) { return showFormWindow(window, this.formWindowCount++); } /** * Shows a new FormWindow to the player * You can find out FormWindow result by listening to PlayerFormRespondedEvent */ public int showFormWindow(FormWindow window, int id) { ModalFormRequestPacket packet = new ModalFormRequestPacket(); packet.formId = id; packet.data = window.getJSONData(); this.formWindows.put(packet.formId, window); this.dataPacket(packet); return id; } /** * Shows a new setting page in game settings * You can find out settings result by listening to PlayerFormRespondedEvent */ public int addServerSettings(FormWindow window) { int id = this.formWindowCount++; this.serverSettings.put(id, window); return id; } /** * Creates and sends a BossBar to the player * * @param text The BossBar message * @param length The BossBar percentage * @return bossBarId The BossBar ID, you should store it if you want to remove or update the BossBar later */ @Deprecated public long createBossBar(String text, int length) { DummyBossBar bossBar = new DummyBossBar.Builder(this).text(text).length(length).build(); return this.createBossBar(bossBar); } /** * Creates and sends a BossBar to the player * * @param dummyBossBar DummyBossBar Object (Instantiate it by the Class Builder) * @return bossBarId The BossBar ID, you should store it if you want to remove or update the BossBar later * @see DummyBossBar.Builder */ public long createBossBar(DummyBossBar dummyBossBar) { this.dummyBossBars.put(dummyBossBar.getBossBarId(), dummyBossBar); dummyBossBar.create(); return dummyBossBar.getBossBarId(); } /** * Get a DummyBossBar object * * @param bossBarId The BossBar ID * @return DummyBossBar object * @see DummyBossBar#setText(String) Set BossBar text * @see DummyBossBar#setLength(float) Set BossBar length * @see DummyBossBar#setColor(Color) Set BossBar color */ public DummyBossBar getDummyBossBar(long bossBarId) { return this.dummyBossBars.getOrDefault(bossBarId, null); } /** * Get all DummyBossBar objects * * @return DummyBossBars Map */ public Map<Long, DummyBossBar> getDummyBossBars() { return dummyBossBars; } /** * Updates a BossBar * * @param text The new BossBar message * @param length The new BossBar length * @param bossBarId The BossBar ID */ @Deprecated public void updateBossBar(String text, int length, long bossBarId) { if (this.dummyBossBars.containsKey(bossBarId)) { DummyBossBar bossBar = this.dummyBossBars.get(bossBarId); bossBar.setText(text); bossBar.setLength(length); } } /** * Removes a BossBar * * @param bossBarId The BossBar ID */ public void removeBossBar(long bossBarId) { if (this.dummyBossBars.containsKey(bossBarId)) { this.dummyBossBars.get(bossBarId).destroy(); this.dummyBossBars.remove(bossBarId); } } public int getWindowId(Inventory inventory) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); } return -1; } public Inventory getWindowById(int id) { return this.windowIndex.get(id); } public int addWindow(Inventory inventory) { return this.addWindow(inventory, null); } public int addWindow(Inventory inventory, Integer forceId) { return addWindow(inventory, forceId, false); } public int addWindow(Inventory inventory, Integer forceId, boolean isPermanent) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); } int cnt; if (forceId == null) { this.windowCnt = cnt = Math.max(4, ++this.windowCnt % 99); } else { cnt = forceId; } this.windowIndex.put(cnt, inventory); this.windows.put(inventory, cnt); if (isPermanent) { this.permanentWindows.add(cnt); } if (inventory.open(this)) { return cnt; } else { this.removeWindow(inventory); return -1; } } public void removeWindow(Inventory inventory) { inventory.close(this); if (this.windows.containsKey(inventory)) { int id = this.windows.get(inventory); this.windows.remove(this.windowIndex.get(id)); this.windowIndex.remove(id); } } public void sendAllInventories() { for (Inventory inv : this.windowIndex.values()) { inv.sendContents(this); if (inv instanceof PlayerInventory) { ((PlayerInventory) inv).sendArmorContents(this); } } } protected void addDefaultWindows() { this.addWindow(this.getInventory(), ContainerIds.INVENTORY, true); this.cursorInventory = new PlayerCursorInventory(this); this.addWindow(this.cursorInventory, ContainerIds.CURSOR, true); this.craftingGrid = new CraftingGrid(this); //TODO: more windows } public PlayerCursorInventory getCursorInventory() { return this.cursorInventory; } public CraftingGrid getCraftingGrid() { return this.craftingGrid; } public void setCraftingGrid(CraftingGrid grid) { this.craftingGrid = grid; } public void resetCraftingGridType() { if (this.craftingGrid != null) { Item[] drops = this.inventory.addItem(this.craftingGrid.getContents().values().stream().toArray(Item[]::new)); if (drops.length > 0) { for (Item drop : drops) { this.dropItem(drop); } } drops = this.inventory.addItem(this.cursorInventory.getItem(0)); if (drops.length > 0) { for (Item drop : drops) { this.dropItem(drop); } } this.cursorInventory.clearAll(); this.craftingGrid.clearAll(); if (this.craftingGrid instanceof BigCraftingGrid) { this.craftingGrid = new CraftingGrid(this); ContainerClosePacket pk = new ContainerClosePacket(); //be sure, big crafting is really closed pk.windowId = ContainerIds.NONE; this.dataPacket(pk); } this.craftingType = 0; } } public void removeAllWindows() { removeAllWindows(false); } public void removeAllWindows(boolean permanent) { for (Entry<Integer, Inventory> entry : new ArrayList<>(this.windowIndex.entrySet())) { if (!permanent && this.permanentWindows.contains(entry.getKey())) { continue; } this.removeWindow(entry.getValue()); } } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { this.server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List<MetadataValue> getMetadata(String metadataKey) { return this.server.getPlayerMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { return this.server.getPlayerMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override public void onChunkChanged(FullChunk chunk) { this.usedChunks.remove(Level.chunkHash(chunk.getX(), chunk.getZ())); } @Override public void onChunkLoaded(FullChunk chunk) { } @Override public void onChunkPopulated(FullChunk chunk) { } @Override public void onChunkUnloaded(FullChunk chunk) { } @Override public void onBlockChanged(Vector3 block) { } @Override public Integer getLoaderId() { return this.loaderId; } @Override public boolean isLoaderActive() { return this.isConnected(); } public static BatchPacket getChunkCacheFromData(int chunkX, int chunkZ, byte[] payload) { FullChunkDataPacket pk = new FullChunkDataPacket(); pk.chunkX = chunkX; pk.chunkZ = chunkZ; pk.data = payload; pk.encode(); BatchPacket batch = new BatchPacket(); byte[][] batchPayload = new byte[2][]; byte[] buf = pk.getBuffer(); batchPayload[0] = Binary.writeUnsignedVarInt(buf.length); batchPayload[1] = buf; byte[] data = Binary.appendBytes(batchPayload); try { batch.payload = Zlib.deflate(data, Server.getInstance().networkCompressionLevel); } catch (Exception e) { throw new RuntimeException(e); } return batch; } private boolean foodEnabled = true; public boolean isFoodEnabled() { return !(this.isCreative() || this.isSpectator()) && this.foodEnabled; } public void setFoodEnabled(boolean foodEnabled) { this.foodEnabled = foodEnabled; } public PlayerFood getFoodData() { return this.foodData; } //todo a lot on dimension public void setDimension(int dimension) { ChangeDimensionPacket pk = new ChangeDimensionPacket(); pk.dimension = getLevel().getDimension(); this.dataPacket(pk); } public void setCheckMovement(boolean checkMovement) { this.checkMovement = checkMovement; } public synchronized void setLocale(Locale locale) { this.locale.set(locale); } public synchronized Locale getLocale() { return this.locale.get(); } public void setSprinting(boolean value, boolean setDefault) { super.setSprinting(value); if (setDefault) { this.movementSpeed = DEFAULT_SPEED; } else { float sprintSpeedChange = DEFAULT_SPEED * 0.3f; if (!value) sprintSpeedChange *= -1; this.movementSpeed += sprintSpeedChange; } this.setMovementSpeed(this.movementSpeed); } public void transfer(InetSocketAddress address) { String hostName = address.getAddress().getHostAddress(); int port = address.getPort(); TransferPacket pk = new TransferPacket(); pk.address = hostName; pk.port = port; this.dataPacket(pk); String message = "Transferred to " + hostName + ":" + port; this.close(message, message, false); } public LoginChainData getLoginChainData() { return this.loginChainData; } public boolean pickupEntity(Entity entity, boolean near) { if (!this.spawned || !this.isAlive() || !this.isOnline() || this.getGamemode() == SPECTATOR) { return false; } if (near) { if (entity instanceof EntityArrow && ((EntityArrow) entity).hadCollision) { ItemArrow item = new ItemArrow(); if (this.isSurvival() && !this.inventory.canAddItem(item)) { return false; } InventoryPickupArrowEvent ev; this.server.getPluginManager().callEvent(ev = new InventoryPickupArrowEvent(this.inventory, (EntityArrow) entity)); if (ev.isCancelled()) { return false; } TakeItemEntityPacket pk = new TakeItemEntityPacket(); pk.entityId = this.getId(); pk.target = entity.getId(); Server.broadcastPacket(entity.getViewers().values(), pk); this.dataPacket(pk); this.inventory.addItem(item.clone()); entity.kill(); return true; } else if (entity instanceof EntityItem) { if (((EntityItem) entity).getPickupDelay() <= 0) { Item item = ((EntityItem) entity).getItem(); if (item != null) { if (this.isSurvival() && !this.inventory.canAddItem(item)) { return false; } InventoryPickupItemEvent ev; this.server.getPluginManager().callEvent(ev = new InventoryPickupItemEvent(this.inventory, (EntityItem) entity)); if (ev.isCancelled()) { return false; } switch (item.getId()) { case Item.WOOD: case Item.WOOD2: this.awardAchievement("mineWood"); break; case Item.DIAMOND: this.awardAchievement("diamond"); break; } /*switch (item.getId()) { case Item.WOOD: this.awardAchievement("mineWood"); break; case Item.DIAMOND: this.awardAchievement("diamond"); break; }*/ TakeItemEntityPacket pk = new TakeItemEntityPacket(); pk.entityId = this.getId(); pk.target = entity.getId(); Server.broadcastPacket(entity.getViewers().values(), pk); this.dataPacket(pk); this.inventory.addItem(item.clone()); entity.kill(); return true; } } } } int tick = this.getServer().getTick(); if (pickedXPOrb < tick && entity instanceof EntityXPOrb && this.boundingBox.isVectorInside(entity)) { EntityXPOrb xpOrb = (EntityXPOrb) entity; if (xpOrb.getPickupDelay() <= 0) { int exp = xpOrb.getExp(); this.addExperience(exp); entity.kill(); this.getLevel().addSound(this, Sound.RANDOM_ORB); pickedXPOrb = tick; return true; } } return false; } @Override public int hashCode() { if ((this.hash == 0) || (this.hash == 485)) { this.hash = (485 + (getUniqueId() != null ? getUniqueId().hashCode() : 0)); } return this.hash; } @Override public boolean equals(Object obj) { if (!(obj instanceof Player)) { return false; } Player other = (Player) obj; return Objects.equals(this.getUniqueId(), other.getUniqueId()) && this.getId() == other.getId(); } /** * Notifies an ACK response from the client * * @param identification */ public void notifyACK(int identification) { needACK.put(identification, Boolean.TRUE); } public boolean isBreakingBlock() { return this.breakingBlock != null; } /** * Show a window of a XBOX account's profile * @param xuid XUID */ public void showXboxProfile(String xuid) { ShowProfilePacket pk = new ShowProfilePacket(); pk.xuid = xuid; this.dataPacket(pk); } }
187,301
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerFood.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/PlayerFood.java
package cn.nukkit; import cn.nukkit.entity.Attribute; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityRegainHealthEvent; import cn.nukkit.event.player.PlayerFoodLevelChangeEvent; import cn.nukkit.item.food.Food; import cn.nukkit.potion.Effect; /** * Created by funcraft on 2015/11/11. */ public class PlayerFood { private int foodLevel = 20; private final int maxFoodLevel; private float foodSaturationLevel = 20f; private int foodTickTimer = 0; private double foodExpLevel = 0; private final Player player; public PlayerFood(Player player, int foodLevel, float foodSaturationLevel) { this.player = player; this.foodLevel = foodLevel; this.maxFoodLevel = 20; this.foodSaturationLevel = foodSaturationLevel; } public Player getPlayer() { return this.player; } public int getLevel() { return this.foodLevel; } public int getMaxLevel() { return this.maxFoodLevel; } public void setLevel(int foodLevel) { this.setLevel(foodLevel, -1); } public void setLevel(int foodLevel, float saturationLevel) { if (foodLevel > 20) { foodLevel = 20; } if (foodLevel < 0) { foodLevel = 0; } if (foodLevel <= 6 && !(this.getLevel() <= 6)) { if (this.getPlayer().isSprinting()) { this.getPlayer().setSprinting(false); } } PlayerFoodLevelChangeEvent ev = new PlayerFoodLevelChangeEvent(this.getPlayer(), foodLevel, saturationLevel); this.getPlayer().getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { this.sendFoodLevel(this.getLevel()); return; } int foodLevel0 = ev.getFoodLevel(); float fsl = ev.getFoodSaturationLevel(); this.foodLevel = foodLevel; if (fsl != -1) { if (fsl > foodLevel) fsl = foodLevel; this.foodSaturationLevel = fsl; } this.foodLevel = foodLevel0; this.sendFoodLevel(); } public float getFoodSaturationLevel() { return this.foodSaturationLevel; } public void setFoodSaturationLevel(float fsl) { if (fsl > this.getLevel()) fsl = this.getLevel(); if (fsl < 0) fsl = 0; PlayerFoodLevelChangeEvent ev = new PlayerFoodLevelChangeEvent(this.getPlayer(), this.getLevel(), fsl); this.getPlayer().getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { return; } fsl = ev.getFoodSaturationLevel(); this.foodSaturationLevel = fsl; } public void useHunger() { this.useHunger(1); } public void useHunger(int amount) { float sfl = this.getFoodSaturationLevel(); int foodLevel = this.getLevel(); if (sfl > 0) { float newSfl = sfl - amount; if (newSfl < 0) newSfl = 0; this.setFoodSaturationLevel(newSfl); } else { this.setLevel(foodLevel - amount); } } public void addFoodLevel(Food food) { this.addFoodLevel(food.getRestoreFood(), food.getRestoreSaturation()); } public void addFoodLevel(int foodLevel, float fsl) { this.setLevel(this.getLevel() + foodLevel, this.getFoodSaturationLevel() + fsl); } public void sendFoodLevel() { this.sendFoodLevel(this.getLevel()); } public void reset() { this.foodLevel = 20; this.foodSaturationLevel = 20; this.foodExpLevel = 0; this.foodTickTimer = 0; this.sendFoodLevel(); } public void sendFoodLevel(int foodLevel) { if (this.getPlayer().spawned) { this.getPlayer().setAttribute(Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(foodLevel)); } } public void update(int tickDiff) { if (!this.getPlayer().isFoodEnabled()) return; if (this.getPlayer().isAlive()) { int diff = Server.getInstance().getDifficulty(); if (this.getLevel() > 17) { this.foodTickTimer += tickDiff; if (this.foodTickTimer >= 80) { if (this.getPlayer().getHealth() < this.getPlayer().getMaxHealth()) { EntityRegainHealthEvent ev = new EntityRegainHealthEvent(this.getPlayer(), 1, EntityRegainHealthEvent.CAUSE_EATING); this.getPlayer().heal(ev); //this.updateFoodExpLevel(3); } this.foodTickTimer = 0; } } else if (this.getLevel() == 0) { this.foodTickTimer += tickDiff; if (this.foodTickTimer >= 80) { EntityDamageEvent ev = new EntityDamageEvent(this.getPlayer(), DamageCause.VOID, 1); float now = this.getPlayer().getHealth(); if (diff == 1) { if (now > 10) this.getPlayer().attack(ev); } else if (diff == 2) { if (now > 1) this.getPlayer().attack(ev); } else { this.getPlayer().attack(ev); } this.foodTickTimer = 0; } } if (this.getPlayer().hasEffect(Effect.HUNGER)) { this.updateFoodExpLevel(0.025); } } } public void updateFoodExpLevel(double use) { if (!this.getPlayer().isFoodEnabled()) return; if (Server.getInstance().getDifficulty() == 0) return; if (this.getPlayer().hasEffect(Effect.SATURATION)) return; this.foodExpLevel += use; if (this.foodExpLevel > 4) { this.useHunger(1); this.foodExpLevel = 0; } } /** * @deprecated use {@link #setLevel(int)} instead **/ @Deprecated public void setFoodLevel(int foodLevel) { setLevel(foodLevel); } /** * @deprecated use {@link #setLevel(int, float)} instead **/ @Deprecated public void setFoodLevel(int foodLevel, float saturationLevel) { setLevel(foodLevel, saturationLevel); } }
6,532
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
AdventureSettings.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/AdventureSettings.java
package cn.nukkit; import cn.nukkit.network.protocol.AdventureSettingsPacket; import java.util.EnumMap; import java.util.Map; /** * Nukkit Project * Author: MagicDroidX */ public class AdventureSettings implements Cloneable { public static final int PERMISSION_NORMAL = 0; public static final int PERMISSION_OPERATOR = 1; public static final int PERMISSION_HOST = 2; public static final int PERMISSION_AUTOMATION = 3; public static final int PERMISSION_ADMIN = 4; private Map<Type, Boolean> values = new EnumMap<>(Type.class); private Player player; public AdventureSettings(Player player) { this.player = player; } public AdventureSettings clone(Player newPlayer) { try { AdventureSettings settings = (AdventureSettings) super.clone(); settings.player = newPlayer; return settings; } catch (CloneNotSupportedException e) { return null; } } public AdventureSettings set(Type type, boolean value) { this.values.put(type, value); return this; } public boolean get(Type type) { Boolean value = this.values.get(type); return value == null ? type.getDefaultValue() : value; } public void update() { AdventureSettingsPacket pk = new AdventureSettingsPacket(); for (Type t : Type.values()) { pk.setFlag(t.getId(), get(t)); } pk.commandPermission = (player.isOp() ? AdventureSettingsPacket.PERMISSION_OPERATOR : AdventureSettingsPacket.PERMISSION_NORMAL); pk.playerPermission = (player.isOp() ? Player.PERMISSION_OPERATOR : Player.PERMISSION_MEMBER); pk.entityUniqueId = player.getId(); Server.broadcastPacket(Server.getInstance().getOnlinePlayers().values(), pk); player.resetInAirTicks(); } public enum Type { WORLD_IMMUTABLE(AdventureSettingsPacket.WORLD_IMMUTABLE, false), AUTO_JUMP(AdventureSettingsPacket.AUTO_JUMP, true), ALLOW_FLIGHT(AdventureSettingsPacket.ALLOW_FLIGHT, false), NO_CLIP(AdventureSettingsPacket.NO_CLIP, false), WORLD_BUILDER(AdventureSettingsPacket.WORLD_BUILDER, true), FLYING(AdventureSettingsPacket.FLYING, false), MUTED(AdventureSettingsPacket.MUTED, false), BUILD_AND_MINE(AdventureSettingsPacket.BUILD_AND_MINE, true), DOORS_AND_SWITCHED(AdventureSettingsPacket.DOORS_AND_SWITCHES, true), OPEN_CONTAINERS(AdventureSettingsPacket.OPEN_CONTAINERS, true), ATTACK_PLAYERS(AdventureSettingsPacket.ATTACK_PLAYERS, true), ATTACK_MOBS(AdventureSettingsPacket.ATTACK_MOBS, true), OPERATOR(AdventureSettingsPacket.OPERATOR, false), TELEPORT(AdventureSettingsPacket.TELEPORT, false); private final int id; private final boolean defaultValue; Type(int id, boolean defaultValue) { this.id = id; this.defaultValue = defaultValue; } public int getId() { return id; } public boolean getDefaultValue() { return this.defaultValue; } } }
3,154
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
InterruptibleThread.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/InterruptibleThread.java
package cn.nukkit; /** * 描述一个可以被中断的线程的接口。<br> * An interface to describe a thread that can be interrupted. * <p> * <p>在Nukkit服务器停止时,Nukkit会找到所有实现了{@code InterruptibleThread}的线程,并逐一中断。<br> * When a Nukkit server is stopping, Nukkit finds all threads implements {@code InterruptibleThread}, * and interrupt them one by one.</p> * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.scheduler.AsyncWorker * @see cn.nukkit.command.CommandReader * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface InterruptibleThread { }
681
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
NBTIO.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/NBTIO.java
package cn.nukkit.nbt; import cn.nukkit.item.Item; import cn.nukkit.nbt.stream.*; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.Tag; import cn.nukkit.utils.ThreadCache; import java.io.*; import java.nio.ByteOrder; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Collection; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPInputStream; public class NBTIO { /** * A Named Binary Tag library for Nukkit Project */ public static CompoundTag putItemHelper(Item item) { return putItemHelper(item, null); } public static CompoundTag putItemHelper(Item item, Integer slot) { CompoundTag tag = new CompoundTag(null) .putShort("id", item.getId()) .putByte("Count", item.getCount()) .putShort("Damage", item.getDamage()); if (slot != null) { tag.putByte("Slot", slot); } if (item.hasCompoundTag()) { tag.putCompound("tag", item.getNamedTag()); } return tag; } public static Item getItemHelper(CompoundTag tag) { if (!tag.contains("id") || !tag.contains("Count")) { return Item.get(0); } Item item; try { item = Item.get(tag.getShort("id"), !tag.contains("Damage") ? 0 : tag.getShort("Damage"), tag.getByte("Count")); } catch (Exception e) { item = Item.fromString(tag.getString("id")); item.setDamage(!tag.contains("Damage") ? 0 : tag.getShort("Damage")); item.setCount(tag.getByte("Count")); } if (tag.contains("tag") && tag.get("tag") instanceof CompoundTag) { item.setNamedTag(tag.getCompound("tag")); } return item; } public static CompoundTag read(File file) throws IOException { return read(file, ByteOrder.BIG_ENDIAN); } public static CompoundTag read(File file, ByteOrder endianness) throws IOException { if (!file.exists()) return null; return read(new FileInputStream(file), endianness); } public static CompoundTag read(InputStream inputStream) throws IOException { return read(inputStream, ByteOrder.BIG_ENDIAN); } public static CompoundTag read(InputStream inputStream, ByteOrder endianness) throws IOException { return read(inputStream, endianness, false); } public static CompoundTag read(InputStream inputStream, ByteOrder endianness, boolean network) throws IOException { try (NBTInputStream stream = new NBTInputStream(inputStream, endianness, network)) { Tag tag = Tag.readNamedTag(stream); if (tag instanceof CompoundTag) { return (CompoundTag) tag; } throw new IOException("Root tag must be a named compound tag"); } } public static CompoundTag read(byte[] data) throws IOException { return read(data, ByteOrder.BIG_ENDIAN); } public static CompoundTag read(byte[] data, ByteOrder endianness) throws IOException { return read(new ByteArrayInputStream(data), endianness); } public static CompoundTag read(byte[] data, ByteOrder endianness, boolean network) throws IOException { return read(new ByteArrayInputStream(data), endianness, network); } public static CompoundTag readCompressed(InputStream inputStream) throws IOException { return readCompressed(inputStream, ByteOrder.BIG_ENDIAN); } public static CompoundTag readCompressed(InputStream inputStream, ByteOrder endianness) throws IOException { return read(new BufferedInputStream(new GZIPInputStream(inputStream)), endianness); } public static CompoundTag readCompressed(byte[] data) throws IOException { return readCompressed(data, ByteOrder.BIG_ENDIAN); } public static CompoundTag readCompressed(byte[] data, ByteOrder endianness) throws IOException { return read(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data))), endianness, true); } public static CompoundTag readNetworkCompressed(InputStream inputStream) throws IOException { return readNetworkCompressed(inputStream, ByteOrder.BIG_ENDIAN); } public static CompoundTag readNetworkCompressed(InputStream inputStream, ByteOrder endianness) throws IOException { return read(new BufferedInputStream(new GZIPInputStream(inputStream)), endianness); } public static CompoundTag readNetworkCompressed(byte[] data) throws IOException { return readNetworkCompressed(data, ByteOrder.BIG_ENDIAN); } public static CompoundTag readNetworkCompressed(byte[] data, ByteOrder endianness) throws IOException { return read(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data))), endianness, true); } public static byte[] write(CompoundTag tag) throws IOException { return write(tag, ByteOrder.BIG_ENDIAN); } public static byte[] write(CompoundTag tag, ByteOrder endianness) throws IOException { return write(tag, endianness, false); } public static byte[] write(CompoundTag tag, ByteOrder endianness, boolean network) throws IOException { FastByteArrayOutputStream baos = ThreadCache.fbaos.get().reset(); try (NBTOutputStream stream = new NBTOutputStream(baos, endianness, network)) { Tag.writeNamedTag(tag, stream); return baos.toByteArray(); } } public static byte[] write(Collection<CompoundTag> tags) throws IOException { return write(tags, ByteOrder.BIG_ENDIAN); } public static byte[] write(Collection<CompoundTag> tags, ByteOrder endianness) throws IOException { return write(tags, endianness, false); } public static byte[] write(Collection<CompoundTag> tags, ByteOrder endianness, boolean network) throws IOException { FastByteArrayOutputStream baos = ThreadCache.fbaos.get().reset(); try (NBTOutputStream stream = new NBTOutputStream(baos, endianness, network)) { for (CompoundTag tag : tags) { Tag.writeNamedTag(tag, stream); } return baos.toByteArray(); } } public static void write(CompoundTag tag, File file) throws IOException { write(tag, file, ByteOrder.BIG_ENDIAN); } public static void write(CompoundTag tag, File file, ByteOrder endianness) throws IOException { write(tag, new FileOutputStream(file), endianness); } public static void write(CompoundTag tag, OutputStream outputStream) throws IOException { write(tag, outputStream, ByteOrder.BIG_ENDIAN); } public static void write(CompoundTag tag, OutputStream outputStream, ByteOrder endianness) throws IOException { write(tag, outputStream, endianness, false); } public static void write(CompoundTag tag, OutputStream outputStream, ByteOrder endianness, boolean network) throws IOException { try (NBTOutputStream stream = new NBTOutputStream(outputStream, endianness, network)) { Tag.writeNamedTag(tag, stream); } } public static byte[] writeGZIPCompressed(CompoundTag tag) throws IOException { return writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN); } public static byte[] writeGZIPCompressed(CompoundTag tag, ByteOrder endianness) throws IOException { FastByteArrayOutputStream baos = ThreadCache.fbaos.get().reset(); writeGZIPCompressed(tag, baos, endianness); return baos.toByteArray(); } public static void writeGZIPCompressed(CompoundTag tag, OutputStream outputStream) throws IOException { writeGZIPCompressed(tag, outputStream, ByteOrder.BIG_ENDIAN); } public static void writeGZIPCompressed(CompoundTag tag, OutputStream outputStream, ByteOrder endianness) throws IOException { write(tag, new PGZIPOutputStream(outputStream), endianness); } public static byte[] writeNetworkGZIPCompressed(CompoundTag tag) throws IOException { return writeNetworkGZIPCompressed(tag, ByteOrder.BIG_ENDIAN); } public static byte[] writeNetworkGZIPCompressed(CompoundTag tag, ByteOrder endianness) throws IOException { FastByteArrayOutputStream baos = ThreadCache.fbaos.get().reset(); writeNetworkGZIPCompressed(tag, baos, endianness); return baos.toByteArray(); } public static void writeNetworkGZIPCompressed(CompoundTag tag, OutputStream outputStream) throws IOException { writeNetworkGZIPCompressed(tag, outputStream, ByteOrder.BIG_ENDIAN); } public static void writeNetworkGZIPCompressed(CompoundTag tag, OutputStream outputStream, ByteOrder endianness) throws IOException { write(tag, new PGZIPOutputStream(outputStream), endianness, true); } public static void writeZLIBCompressed(CompoundTag tag, OutputStream outputStream) throws IOException { writeZLIBCompressed(tag, outputStream, ByteOrder.BIG_ENDIAN); } public static void writeZLIBCompressed(CompoundTag tag, OutputStream outputStream, ByteOrder endianness) throws IOException { writeZLIBCompressed(tag, outputStream, Deflater.DEFAULT_COMPRESSION, endianness); } public static void writeZLIBCompressed(CompoundTag tag, OutputStream outputStream, int level) throws IOException { writeZLIBCompressed(tag, outputStream, level, ByteOrder.BIG_ENDIAN); } public static void writeZLIBCompressed(CompoundTag tag, OutputStream outputStream, int level, ByteOrder endianness) throws IOException { write(tag, new DeflaterOutputStream(outputStream, new Deflater(level)), endianness); } public static void safeWrite(CompoundTag tag, File file) throws IOException { File tmpFile = new File(file.getAbsolutePath() + "_tmp"); if (tmpFile.exists()) { tmpFile.delete(); } write(tag, tmpFile); Files.move(tmpFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } }
10,160
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CompoundTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/CompoundTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class CompoundTag extends Tag implements Cloneable { private final Map<String, Tag> tags = new HashMap<>(); public CompoundTag() { super(""); } public CompoundTag(String name) { super(name); } @Override public void write(NBTOutputStream dos) throws IOException { for (Tag tag : tags.values()) { Tag.writeNamedTag(tag, dos); } dos.writeByte(Tag.TAG_End); } @Override public void load(NBTInputStream dis) throws IOException { tags.clear(); Tag tag; while ((tag = Tag.readNamedTag(dis)).getId() != Tag.TAG_End) { tags.put(tag.getName(), tag); } } public Collection<Tag> getAllTags() { return tags.values(); } @Override public byte getId() { return TAG_Compound; } public CompoundTag put(String name, Tag tag) { tags.put(name, tag.setName(name)); return this; } public CompoundTag putByte(String name, int value) { tags.put(name, new ByteTag(name, value)); return this; } public CompoundTag putShort(String name, int value) { tags.put(name, new ShortTag(name, value)); return this; } public CompoundTag putInt(String name, int value) { tags.put(name, new IntTag(name, value)); return this; } public CompoundTag putLong(String name, long value) { tags.put(name, new LongTag(name, value)); return this; } public CompoundTag putFloat(String name, float value) { tags.put(name, new FloatTag(name, value)); return this; } public CompoundTag putDouble(String name, double value) { tags.put(name, new DoubleTag(name, value)); return this; } public CompoundTag putString(String name, String value) { tags.put(name, new StringTag(name, value)); return this; } public CompoundTag putByteArray(String name, byte[] value) { tags.put(name, new ByteArrayTag(name, value)); return this; } public CompoundTag putIntArray(String name, int[] value) { tags.put(name, new IntArrayTag(name, value)); return this; } public CompoundTag putList(ListTag<? extends Tag> listTag) { tags.put(listTag.getName(), listTag); return this; } public CompoundTag putCompound(String name, CompoundTag value) { tags.put(name, value.setName(name)); return this; } public CompoundTag putBoolean(String string, boolean val) { putByte(string, val ? 1 : 0); return this; } public Tag get(String name) { return tags.get(name); } public boolean contains(String name) { return tags.containsKey(name); } public CompoundTag remove(String name) { tags.remove(name); return this; } public int getByte(String name) { if (!tags.containsKey(name)) return (byte) 0; return ((NumberTag) tags.get(name)).getData().intValue(); } public int getShort(String name) { if (!tags.containsKey(name)) return 0; return ((NumberTag) tags.get(name)).getData().intValue(); } public int getInt(String name) { if (!tags.containsKey(name)) return 0; return ((NumberTag) tags.get(name)).getData().intValue(); } public long getLong(String name) { if (!tags.containsKey(name)) return (long) 0; return ((NumberTag) tags.get(name)).getData().longValue(); } public float getFloat(String name) { if (!tags.containsKey(name)) return (float) 0; return ((NumberTag) tags.get(name)).getData().floatValue(); } public double getDouble(String name) { if (!tags.containsKey(name)) return (double) 0; return ((NumberTag) tags.get(name)).getData().doubleValue(); } public String getString(String name) { if (!tags.containsKey(name)) return ""; Tag tag = tags.get(name); if (tag instanceof NumberTag) { return String.valueOf(((NumberTag) tag).getData()); } return ((StringTag) tag).data; } public byte[] getByteArray(String name) { if (!tags.containsKey(name)) return new byte[0]; return ((ByteArrayTag) tags.get(name)).data; } public int[] getIntArray(String name) { if (!tags.containsKey(name)) return new int[0]; return ((IntArrayTag) tags.get(name)).data; } public CompoundTag getCompound(String name) { if (!tags.containsKey(name)) return new CompoundTag(name); return (CompoundTag) tags.get(name); } @SuppressWarnings("unchecked") public ListTag<? extends Tag> getList(String name) { if (!tags.containsKey(name)) return new ListTag<>(name); return (ListTag<? extends Tag>) tags.get(name); } @SuppressWarnings("unchecked") public <T extends Tag> ListTag<T> getList(String name, Class<T> type) { if (tags.containsKey(name)) { return (ListTag<T>) tags.get(name); } return new ListTag<>(name); } public Map<String, Tag> getTags() { return new HashMap<>(this.tags); } public boolean getBoolean(String name) { return getByte(name) != 0; } public String toString() { return "CompoundTag " + this.getName() + " (" + tags.size() + " entries)"; } public void print(String prefix, PrintStream out) { super.print(prefix, out); out.println(prefix + "{"); String orgPrefix = prefix; prefix += " "; for (Tag tag : tags.values()) { tag.print(prefix, out); } out.println(orgPrefix + "}"); } public boolean isEmpty() { return tags.isEmpty(); } public CompoundTag copy() { CompoundTag tag = new CompoundTag(getName()); for (String key : tags.keySet()) { tag.put(key, tags.get(key).copy()); } return tag; } @Override public boolean equals(Object obj) { if (super.equals(obj)) { CompoundTag o = (CompoundTag) obj; return tags.entrySet().equals(o.tags.entrySet()); } return false; } /** * Check existence of NBT tag * * @param name - NBT tag Id. * @return - true, if tag exists */ public boolean exist(String name) { return tags.containsKey(name); } @Override public CompoundTag clone() { CompoundTag nbt = new CompoundTag(); this.getTags().forEach((key, value) -> nbt.put(key, value.copy())); return nbt; } }
6,933
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ListTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/ListTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ListTag<T extends Tag> extends Tag { private List<T> list = new ArrayList<>(); public byte type; public ListTag() { super(""); } public ListTag(String name) { super(name); } @Override void write(NBTOutputStream dos) throws IOException { if (list.size() > 0) type = list.get(0).getId(); else type = 1; dos.writeByte(type); dos.writeInt(list.size()); for (T aList : list) aList.write(dos); } @Override @SuppressWarnings("unchecked") void load(NBTInputStream dis) throws IOException { type = dis.readByte(); int size = dis.readInt(); list = new ArrayList<>(); for (int i = 0; i < size; i++) { Tag tag = Tag.newTag(type, null); tag.load(dis); list.add((T) tag); } } @Override public byte getId() { return TAG_List; } @Override public String toString() { return "ListTag " + this.getName() + " [" + list.size() + " entries of type " + Tag.getTagName(type) + "]"; } public void print(String prefix, PrintStream out) { super.print(prefix, out); out.println(prefix + "{"); String orgPrefix = prefix; prefix += " "; for (T aList : list) aList.print(prefix, out); out.println(orgPrefix + "}"); } public ListTag<T> add(T tag) { type = tag.getId(); list.add(tag); return this; } public ListTag<T> add(int index, T tag) { type = tag.getId(); if (index >= list.size()) { list.add(index, tag); } else { list.set(index, tag); } return this; } public T get(int index) { return list.get(index); } public List<T> getAll() { return new ArrayList<>(list); } public void setAll(List<T> tags) { this.list = new ArrayList<>(tags); } public void remove(T tag) { list.remove(tag); } public void remove(int index) { list.remove(index); } public void removeAll(Collection<T> tags) { list.remove(tags); } public int size() { return list.size(); } @Override public Tag copy() { ListTag<T> res = new ListTag<>(getName()); res.type = type; for (T t : list) { @SuppressWarnings("unchecked") T copy = (T) t.copy(); res.list.add(copy); } return res; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (super.equals(obj)) { ListTag o = (ListTag) obj; if (type == o.type) { return list.equals(o.list); } } return false; } }
3,088
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
NumberTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/NumberTag.java
package cn.nukkit.nbt.tag; /** * author: MagicDroidX * Nukkit Project */ public abstract class NumberTag<T extends Number> extends Tag { protected NumberTag(String name) { super(name); } public abstract T getData(); public abstract void setData(T data); }
286
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
IntArrayTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/IntArrayTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; import java.util.Arrays; public class IntArrayTag extends Tag { public int[] data; public IntArrayTag(String name) { super(name); } public IntArrayTag(String name, int[] data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeInt(data.length); for (int aData : data) { dos.writeInt(aData); } } @Override void load(NBTInputStream dis) throws IOException { int length = dis.readInt(); data = new int[length]; for (int i = 0; i < length; i++) { data[i] = dis.readInt(); } } @Override public byte getId() { return TAG_Int_Array; } @Override public String toString() { return "IntArrayTag " + this.getName() + " [" + data.length + " bytes]"; } @Override public boolean equals(Object obj) { if (super.equals(obj)) { IntArrayTag intArrayTag = (IntArrayTag) obj; return ((data == null && intArrayTag.data == null) || (data != null && Arrays.equals(data, intArrayTag.data))); } return false; } @Override public Tag copy() { int[] cp = new int[data.length]; System.arraycopy(data, 0, cp, 0, data.length); return new IntArrayTag(getName(), cp); } }
1,534
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
IntTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/IntTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class IntTag extends NumberTag<Integer> { public int data; @Override public Integer getData() { return data; } @Override public void setData(Integer data) { this.data = data == null ? 0 : data; } public IntTag(String name) { super(name); } public IntTag(String name, int data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeInt(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readInt(); } @Override public byte getId() { return TAG_Int; } @Override public String toString() { return "IntTag " + this.getName() + "(data: " + data + ")"; } @Override public Tag copy() { return new IntTag(getName(), data); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { IntTag o = (IntTag) obj; return data == o.data; } return false; } }
1,247
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
FloatTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/FloatTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class FloatTag extends NumberTag<Float> { public float data; @Override public Float getData() { return data; } @Override public void setData(Float data) { this.data = data == null ? 0 : data; } public FloatTag(String name) { super(name); } public FloatTag(String name, float data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeFloat(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readFloat(); } @Override public byte getId() { return TAG_Float; } @Override public String toString() { return "FloatTag " + this.getName() + " (data: " + data + ")"; } @Override public Tag copy() { return new FloatTag(getName(), data); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { FloatTag o = (FloatTag) obj; return data == o.data; } return false; } }
1,266
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ShortTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/ShortTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class ShortTag extends NumberTag<Integer> { public int data; @Override public Integer getData() { return data; } @Override public void setData(Integer data) { this.data = data == null ? 0 : data; } public ShortTag(String name) { super(name); } public ShortTag(String name, int data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeShort(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readUnsignedShort(); } @Override public byte getId() { return TAG_Short; } @Override public String toString() { return "" + data; } @Override public Tag copy() { return new ShortTag(getName(), data); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { ShortTag o = (ShortTag) obj; return data == o.data; } return false; } }
1,231
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
EndTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/EndTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class EndTag extends Tag { public EndTag() { super(null); } @Override void load(NBTInputStream dis) throws IOException { } @Override void write(NBTOutputStream dos) throws IOException { } @Override public byte getId() { return TAG_End; } @Override public String toString() { return "EndTag"; } @Override public Tag copy() { return new EndTag(); } }
610
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
LongTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/LongTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class LongTag extends NumberTag<Long> { public long data; @Override public Long getData() { return data; } @Override public void setData(Long data) { this.data = data == null ? 0 : data; } public LongTag(String name) { super(name); } public LongTag(String name, long data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeLong(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readLong(); } @Override public byte getId() { return TAG_Long; } @Override public String toString() { return "LongTag " + this.getName() + " (data:" + data + ")"; } @Override public Tag copy() { return new LongTag(getName(), data); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { LongTag o = (LongTag) obj; return data == o.data; } return false; } }
1,250
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
DoubleTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/DoubleTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class DoubleTag extends NumberTag<Double> { public double data; @Override public Double getData() { return data; } @Override public void setData(Double data) { this.data = data == null ? 0 : data; } public DoubleTag(String name) { super(name); } public DoubleTag(String name, double data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeDouble(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readDouble(); } @Override public byte getId() { return TAG_Double; } @Override public String toString() { return "DoubleTag " + this.getName() + " (data: " + data + ")"; } @Override public Tag copy() { return new DoubleTag(getName(), data); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { DoubleTag o = (DoubleTag) obj; return data == o.data; } return false; } }
1,281
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ByteTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/ByteTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class ByteTag extends NumberTag<Integer> { public int data; @Override public Integer getData() { return data; } @Override public void setData(Integer data) { this.data = data == null ? 0 : data; } public ByteTag(String name) { super(name); } public ByteTag(String name, int data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { dos.writeByte(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readByte(); } @Override public byte getId() { return TAG_Byte; } @Override public String toString() { String hex = Integer.toHexString(this.data); if (hex.length() < 2) { hex = "0" + hex; } return "ByteTag " + this.getName() + " (data: 0x" + hex + ")"; } @Override public boolean equals(Object obj) { if (super.equals(obj)) { ByteTag byteTag = (ByteTag) obj; return data == byteTag.data; } return false; } @Override public Tag copy() { return new ByteTag(getName(), data); } }
1,394
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ByteArrayTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/ByteArrayTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import cn.nukkit.utils.Binary; import java.io.IOException; import java.util.Arrays; public class ByteArrayTag extends Tag { public byte[] data; public ByteArrayTag(String name) { super(name); } public ByteArrayTag(String name, byte[] data) { super(name); this.data = data; } @Override void write(NBTOutputStream dos) throws IOException { if (data == null) { dos.writeInt(0); return; } dos.writeInt(data.length); dos.write(data); } @Override void load(NBTInputStream dis) throws IOException { int length = dis.readInt(); data = new byte[length]; dis.readFully(data); } @Override public byte getId() { return TAG_Byte_Array; } @Override public String toString() { return "ByteArrayTag " + this.getName() + " (data: 0x" + Binary.bytesToHexString(data, true) + " [" + data.length + " bytes])"; } @Override public boolean equals(Object obj) { if (super.equals(obj)) { ByteArrayTag byteArrayTag = (ByteArrayTag) obj; return ((data == null && byteArrayTag.data == null) || (data != null && Arrays.equals(data, byteArrayTag.data))); } return false; } @Override public Tag copy() { byte[] cp = new byte[data.length]; System.arraycopy(data, 0, cp, 0, data.length); return new ByteArrayTag(getName(), cp); } }
1,610
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Tag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/Tag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; import java.io.PrintStream; public abstract class Tag { public static final byte TAG_End = 0; public static final byte TAG_Byte = 1; public static final byte TAG_Short = 2; public static final byte TAG_Int = 3; public static final byte TAG_Long = 4; public static final byte TAG_Float = 5; public static final byte TAG_Double = 6; public static final byte TAG_Byte_Array = 7; public static final byte TAG_String = 8; public static final byte TAG_List = 9; public static final byte TAG_Compound = 10; public static final byte TAG_Int_Array = 11; private String name; abstract void write(NBTOutputStream dos) throws IOException; abstract void load(NBTInputStream dis) throws IOException; public abstract String toString(); public abstract byte getId(); protected Tag(String name) { if (name == null) { this.name = ""; } else { this.name = name; } } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Tag)) { return false; } Tag o = (Tag) obj; return getId() == o.getId() && !(name == null && o.name != null || name != null && o.name == null) && !(name != null && !name.equals(o.name)); } public void print(PrintStream out) { print("", out); } public void print(String prefix, PrintStream out) { String name = getName(); out.print(prefix); out.print(getTagName(getId())); if (name.length() > 0) { out.print("(\"" + name + "\")"); } out.print(": "); out.println(toString()); } public Tag setName(String name) { if (name == null) { this.name = ""; } else { this.name = name; } return this; } public String getName() { if (name == null) return ""; return name; } public static Tag readNamedTag(NBTInputStream dis) throws IOException { byte type = dis.readByte(); if (type == 0) return new EndTag(); String name = dis.readUTF(); Tag tag = newTag(type, name); tag.load(dis); return tag; } public static void writeNamedTag(Tag tag, NBTOutputStream dos) throws IOException { dos.writeByte(tag.getId()); if (tag.getId() == Tag.TAG_End) return; dos.writeUTF(tag.getName()); tag.write(dos); } public static Tag newTag(byte type, String name) { switch (type) { case TAG_End: return new EndTag(); case TAG_Byte: return new ByteTag(name); case TAG_Short: return new ShortTag(name); case TAG_Int: return new IntTag(name); case TAG_Long: return new LongTag(name); case TAG_Float: return new FloatTag(name); case TAG_Double: return new DoubleTag(name); case TAG_Byte_Array: return new ByteArrayTag(name); case TAG_Int_Array: return new IntArrayTag(name); case TAG_String: return new StringTag(name); case TAG_List: return new ListTag<>(name); case TAG_Compound: return new CompoundTag(name); } return new EndTag(); } public static String getTagName(byte type) { switch (type) { case TAG_End: return "TAG_End"; case TAG_Byte: return "TAG_Byte"; case TAG_Short: return "TAG_Short"; case TAG_Int: return "TAG_Int"; case TAG_Long: return "TAG_Long"; case TAG_Float: return "TAG_Float"; case TAG_Double: return "TAG_Double"; case TAG_Byte_Array: return "TAG_Byte_Array"; case TAG_Int_Array: return "TAG_Int_Array"; case TAG_String: return "TAG_String"; case TAG_List: return "TAG_List"; case TAG_Compound: return "TAG_Compound"; } return "UNKNOWN"; } public abstract Tag copy(); }
4,553
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
StringTag.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/tag/StringTag.java
package cn.nukkit.nbt.tag; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; import java.io.IOException; public class StringTag extends Tag { public String data; public StringTag(String name) { super(name); } public StringTag(String name, String data) { super(name); this.data = data; if (data == null) throw new IllegalArgumentException("Empty string not allowed"); } @Override void write(NBTOutputStream dos) throws IOException { dos.writeUTF(data); } @Override void load(NBTInputStream dis) throws IOException { data = dis.readUTF(); } @Override public byte getId() { return TAG_String; } @Override public String toString() { return "StringTag " + this.getName() + " (data: " + data + ")"; } @Override public Tag copy() { return new StringTag(getName(), data); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { StringTag o = (StringTag) obj; return ((data == null && o.data == null) || (data != null && data.equals(o.data))); } return false; } }
1,235
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PGZIPBlock.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/PGZIPBlock.java
package cn.nukkit.nbt.stream; import java.util.concurrent.Callable; public class PGZIPBlock implements Callable<byte[]> { public PGZIPBlock(final PGZIPOutputStream parent) { STATE = new PGZIPThreadLocal(parent); } /** * This ThreadLocal avoids the recycling of a lot of memory, causing lumpy performance. */ protected final ThreadLocal<PGZIPState> STATE; public static final int SIZE = 64 * 1024; // private final int index; protected final byte[] in = new byte[SIZE]; protected int in_length = 0; /* public Block(@Nonnegative int index) { this.index = index; } */ // Only on worker thread @Override public byte[] call() throws Exception { // LOG.info("Processing " + this + " on " + Thread.currentThread()); PGZIPState state = STATE.get(); // ByteArrayOutputStream buf = new ByteArrayOutputStream(in.length); // Overestimate output size required. // DeflaterOutputStream def = newDeflaterOutputStream(buf); state.def.reset(); state.buf.reset(); state.str.write(in, 0, in_length); state.str.flush(); // return Arrays.copyOf(in, in_length); return state.buf.toByteArray(); } @Override public String toString() { return "Block" /* + index */ + "(" + in_length + "/" + in.length + " bytes)"; } }
1,391
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PGZIPOutputStream.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/PGZIPOutputStream.java
package cn.nukkit.nbt.stream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.concurrent.*; import java.util.zip.CRC32; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; /** * A multi-threaded version of {@link java.util.zip.GZIPOutputStream}. * * @author shevek */ public class PGZIPOutputStream extends FilterOutputStream { private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool(); public static ExecutorService getSharedThreadPool() { return EXECUTOR; } // private static final Logger LOG = LoggerFactory.getLogger(PGZIPOutputStream.class); private final static int GZIP_MAGIC = 0x8b1f; // todo: remove after block guessing is implemented // array list that contains the block sizes ArrayList<Integer> blockSizes = new ArrayList<Integer>(); private int level = Deflater.BEST_SPEED; private int strategy = Deflater.DEFAULT_STRATEGY; protected Deflater newDeflater() { Deflater def = new Deflater(level, true); def.setStrategy(strategy); return def; } public void setStrategy(int strategy) { this.strategy = strategy; } public void setLevel(int level) { this.level = level; } protected static DeflaterOutputStream newDeflaterOutputStream(OutputStream out, Deflater deflater) { return new DeflaterOutputStream(out, deflater, 512, true); } // TODO: Share, daemonize. private final ExecutorService executor; private final int nthreads; private final CRC32 crc = new CRC32(); private final BlockingQueue<Future<byte[]>> emitQueue; private PGZIPBlock block = new PGZIPBlock(this/* 0 */); /** * Used as a sentinel for 'closed'. */ private int bytesWritten = 0; // Master thread only public PGZIPOutputStream(OutputStream out, ExecutorService executor, int nthreads) throws IOException { super(out); this.executor = executor; this.nthreads = nthreads; this.emitQueue = new ArrayBlockingQueue<Future<byte[]>>(nthreads); writeHeader(); } /** * Creates a PGZIPOutputStream * using {@link PGZIPOutputStream#getSharedThreadPool()}. * * @param out the eventual output stream for the compressed data. * @throws java.io.IOException if it all goes wrong. */ public PGZIPOutputStream(OutputStream out, int nthreads) throws IOException { this(out, PGZIPOutputStream.getSharedThreadPool(), nthreads); } /** * Creates a PGZIPOutputStream * using {@link PGZIPOutputStream#getSharedThreadPool()} * and {@link Runtime#availableProcessors()}. * * @param out the eventual output stream for the compressed data. * @throws java.io.IOException if it all goes wrong. */ public PGZIPOutputStream(OutputStream out) throws IOException { this(out, Runtime.getRuntime().availableProcessors()); } /* * @see http://www.gzip.org/zlib/rfc-gzip.html#file-format */ private void writeHeader() throws IOException { out.write(new byte[]{ (byte) GZIP_MAGIC, // ID1: Magic number (little-endian short) (byte) (GZIP_MAGIC >> 8), // ID2: Magic number (little-endian short) Deflater.DEFLATED, // CM: Compression method 0, // FLG: Flags (byte) 0, 0, 0, 0, // MTIME: Modification time (int) 0, // XFL: Extra flags 3 // OS: Operating system (3 = Linux) }); } // Master thread only @Override public void write(int b) throws IOException { byte[] single = new byte[1]; single[0] = (byte) (b & 0xFF); write(single); } // Master thread only @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } // Master thread only @Override public void write(byte[] b, int off, int len) throws IOException { crc.update(b, off, len); bytesWritten += len; while (len > 0) { // assert block.in_length < block.in.length int capacity = block.in.length - block.in_length; if (len >= capacity) { System.arraycopy(b, off, block.in, block.in_length, capacity); block.in_length += capacity; // == block.in.length off += capacity; len -= capacity; submit(); } else { System.arraycopy(b, off, block.in, block.in_length, len); block.in_length += len; // off += len; // len = 0; break; } } } // Master thread only private void submit() throws IOException { emitUntil(nthreads - 1); emitQueue.add(executor.submit(block)); block = new PGZIPBlock(this/* block.index + 1 */); } // Emit If Available - submit always // Emit At Least one - submit when executor is full // Emit All Remaining - flush(), close() // Master thread only private void tryEmit() throws IOException, InterruptedException, ExecutionException { for (; ; ) { Future<byte[]> future = emitQueue.peek(); // LOG.info("Peeked future " + future); if (future == null) return; if (!future.isDone()) return; // It's an ordered queue. This MUST be the same element as above. emitQueue.remove(); byte[] toWrite = future.get(); blockSizes.add(toWrite.length); // todo: remove after block guessing is implemented out.write(toWrite); } } // Master thread only /** * Emits any opportunistically available blocks. Furthermore, emits blocks until the number of executing tasks is less than taskCountAllowed. */ private void emitUntil(int taskCountAllowed) throws IOException { try { while (emitQueue.size() > taskCountAllowed) { // LOG.info("Waiting for taskCount=" + emitQueue.size() + " -> " + taskCountAllowed); Future<byte[]> future = emitQueue.remove(); // Valid because emitQueue.size() > 0 byte[] toWrite = future.get(); // Blocks until this task is done. blockSizes.add(toWrite.length); // todo: remove after block guessing is implemented out.write(toWrite); } // We may have achieved more opportunistically available blocks // while waiting for a block above. Let's emit them here. tryEmit(); } catch (ExecutionException e) { throw new IOException(e); } catch (InterruptedException e) { throw new InterruptedIOException(); } } // Master thread only @Override public void flush() throws IOException { // LOG.info("Flush: " + block); if (block.in_length > 0) submit(); emitUntil(0); super.flush(); } // Master thread only @Override public void close() throws IOException { // LOG.info("Closing: bytesWritten=" + bytesWritten); if (bytesWritten >= 0) { flush(); newDeflaterOutputStream(out, newDeflater()).finish(); ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.LITTLE_ENDIAN); // LOG.info("CRC is " + crc.getValue()); buf.putInt((int) crc.getValue()); buf.putInt(bytesWritten); out.write(buf.array()); // allocate() guarantees a backing array. // LOG.info("trailer is " + Arrays.toString(buf.array())); out.flush(); out.close(); bytesWritten = Integer.MIN_VALUE; // } else { // LOG.warn("Already closed."); } } }
8,115
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PGZIPState.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/PGZIPState.java
package cn.nukkit.nbt.stream; import java.io.ByteArrayOutputStream; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; public class PGZIPState { protected final DeflaterOutputStream str; protected final ByteArrayOutputStream buf; protected final Deflater def; public PGZIPState(PGZIPOutputStream parent) { this.def = parent.newDeflater(); this.buf = new ByteArrayOutputStream(PGZIPBlock.SIZE); this.str = parent.newDeflaterOutputStream(buf, def); } }
523
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
NBTOutputStream.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/NBTOutputStream.java
package cn.nukkit.nbt.stream; import cn.nukkit.utils.VarInt; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; /** * author: MagicDroidX * Nukkit Project */ public class NBTOutputStream implements DataOutput, AutoCloseable { private final DataOutputStream stream; private final ByteOrder endianness; private final boolean network; public NBTOutputStream(OutputStream stream) { this(stream, ByteOrder.BIG_ENDIAN); } public NBTOutputStream(OutputStream stream, ByteOrder endianness) { this(stream, endianness, false); } public NBTOutputStream(OutputStream stream, ByteOrder endianness, boolean network) { this.stream = stream instanceof DataOutputStream ? (DataOutputStream) stream : new DataOutputStream(stream); this.endianness = endianness; this.network = network; } public ByteOrder getEndianness() { return endianness; } public boolean isNetwork() { return network; } @Override public void write(byte[] bytes) throws IOException { this.stream.write(bytes); } @Override public void write(byte b[], int off, int len) throws IOException { this.stream.write(b, off, len); } @Override public void write(int b) throws IOException { this.stream.write(b); } @Override public void writeBoolean(boolean v) throws IOException { this.stream.writeBoolean(v); } @Override public void writeByte(int v) throws IOException { this.stream.writeByte(v); } @Override public void writeShort(int v) throws IOException { if (endianness == ByteOrder.LITTLE_ENDIAN) { v = Integer.reverseBytes(v) >> 16; } this.stream.writeShort(v); } @Override public void writeChar(int v) throws IOException { if (endianness == ByteOrder.LITTLE_ENDIAN) { v = Character.reverseBytes((char) v); } this.stream.writeChar(v); } @Override public void writeInt(int v) throws IOException { if (network) { VarInt.writeVarInt(this.stream, v); } else { if (endianness == ByteOrder.LITTLE_ENDIAN) { v = Integer.reverseBytes(v); } this.stream.writeInt(v); } } @Override public void writeLong(long v) throws IOException { if (network) { VarInt.writeVarLong(this.stream, v); } else { if (endianness == ByteOrder.LITTLE_ENDIAN) { v = Long.reverseBytes(v); } this.stream.writeLong(v); } } @Override public void writeFloat(float v) throws IOException { this.writeInt(Float.floatToIntBits(v)); } @Override public void writeDouble(double v) throws IOException { this.writeLong(Double.doubleToLongBits(v)); } @Override public void writeBytes(String s) throws IOException { this.stream.writeBytes(s); } @Override public void writeChars(String s) throws IOException { this.stream.writeChars(s); } @Override public void writeUTF(String s) throws IOException { byte[] bytes = s.getBytes(StandardCharsets.UTF_8); if (network) { VarInt.writeUnsignedVarInt(stream, bytes.length); } else { this.writeShort(bytes.length); } this.stream.write(bytes); } @Override public void close() throws IOException { this.stream.close(); } }
3,701
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BufferedRandomAccessFile.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/BufferedRandomAccessFile.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.nukkit.nbt.stream; import java.io.*; import java.util.Arrays; /** * A <code>BufferedRandomAccessFile</code> is like a * <code>RandomAccessFile</code>, but it uses a private buffer so that most * operations do not require a disk access. * <P> * * Note: The operations on this class are unmonitored. Also, the correct * functioning of the <code>RandomAccessFile</code> methods that are not * overridden here relies on the implementation of those methods in the * superclass. * Author : Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik ( pmalik@facebook.com ) */ public class BufferedRandomAccessFile extends RandomAccessFile { static final int LogBuffSz_ = 16; // 64K buffer public static final int BuffSz_ = (1 << LogBuffSz_); static final long BuffMask_ = ~(((long) BuffSz_) - 1L); /* * This implementation is based on the buffer implementation in Modula-3's * "Rd", "Wr", "RdClass", and "WrClass" interfaces. */ private boolean dirty_; // true iff unflushed bytes exist private boolean closed_; // true iff the file is closed private long curr_; // current position in file private long lo_, hi_; // bounds on characters in "buff" private byte[] buff_; // local buffer private long maxHi_; // this.lo + this.buff.length private boolean hitEOF_; // buffer contains last file block? private long diskPos_; // disk position /* * To describe the above fields, we introduce the following abstractions for * the file "f": * * len(f) the length of the file curr(f) the current position in the file * c(f) the abstract contents of the file disk(f) the contents of f's * backing disk file closed(f) true iff the file is closed * * "curr(f)" is an index in the closed interval [0, len(f)]. "c(f)" is a * character sequence of length "len(f)". "c(f)" and "disk(f)" may differ if * "c(f)" contains unflushed writes not reflected in "disk(f)". The flush * operation has the effect of making "disk(f)" identical to "c(f)". * * A file is said to be *valid* if the following conditions hold: * * V1. The "closed" and "curr" fields are correct: * * f.closed == closed(f) f.curr == curr(f) * * V2. The current position is either contained in the buffer, or just past * the buffer: * * f.lo <= f.curr <= f.hi * * V3. Any (possibly) unflushed characters are stored in "f.buff": * * (forall i in [f.lo, f.curr): c(f)[i] == f.buff[i - f.lo]) * * V4. For all characters not covered by V3, c(f) and disk(f) agree: * * (forall i in [f.lo, len(f)): i not in [f.lo, f.curr) => c(f)[i] == * disk(f)[i]) * * V5. "f.dirty" is true iff the buffer contains bytes that should be * flushed to the file; by V3 and V4, only part of the buffer can be dirty. * * f.dirty == (exists i in [f.lo, f.curr): c(f)[i] != f.buff[i - f.lo]) * * V6. this.maxHi == this.lo + this.buff.length * * Note that "f.buff" can be "null" in a valid file, since the range of * characters in V3 is empty when "f.lo == f.curr". * * A file is said to be *ready* if the buffer contains the current position, * i.e., when: * * R1. !f.closed && f.buff != null && f.lo <= f.curr && f.curr < f.hi * * When a file is ready, reading or writing a single byte can be performed * by reading or writing the in-memory buffer without performing a disk * operation. */ /** * Open a new <code>BufferedRandomAccessFile</code> on <code>file</code> * in mode <code>mode</code>, which should be "r" for reading only, or * "rw" for reading and writing. */ public BufferedRandomAccessFile(File file, String mode) throws IOException { super(file, mode); this.init(0); } public BufferedRandomAccessFile(File file, String mode, int size) throws IOException { super(file, mode); this.init(size); } /** * Open a new <code>BufferedRandomAccessFile</code> on the file named * <code>name</code> in mode <code>mode</code>, which should be "r" for * reading only, or "rw" for reading and writing. */ public BufferedRandomAccessFile(String name, String mode) throws IOException { super(name, mode); this.init(0); } public BufferedRandomAccessFile(String name, String mode, int size) throws FileNotFoundException { super(name, mode); this.init(size); } private void init(int size) { this.dirty_ = this.closed_ = false; this.lo_ = this.curr_ = this.hi_ = 0; this.buff_ = (size > BuffSz_) ? new byte[size] : new byte[BuffSz_]; this.maxHi_ = (long) BuffSz_; this.hitEOF_ = false; this.diskPos_ = 0L; } @Override public void close() throws IOException { this.flush(); this.closed_ = true; super.close(); } /** * Flush any bytes in the file's buffer that have not yet been written to * disk. If the file was created read-only, this method is a no-op. */ public void flush() throws IOException { this.flushBuffer(); } /* Flush any dirty bytes in the buffer to disk. */ private void flushBuffer() throws IOException { if (this.dirty_) { if (this.diskPos_ != this.lo_) super.seek(this.lo_); int len = (int) (this.curr_ - this.lo_); super.write(this.buff_, 0, len); this.diskPos_ = this.curr_; this.dirty_ = false; } } /* * Read at most "this.buff.length" bytes into "this.buff", returning the * number of bytes read. If the return result is less than * "this.buff.length", then EOF was read. */ private int fillBuffer() throws IOException { int cnt = 0; int rem = this.buff_.length; while (rem > 0) { int n = super.read(this.buff_, cnt, rem); if (n < 0) break; cnt += n; rem -= n; } if ( (cnt < 0) && (this.hitEOF_ = (cnt < this.buff_.length)) ) { // make sure buffer that wasn't read is initialized with -1 Arrays.fill(this.buff_, cnt, this.buff_.length, (byte) 0xff); } this.diskPos_ += cnt; return cnt; } /* * This method positions <code>this.curr</code> at position <code>pos</code>. * If <code>pos</code> does not fall in the current buffer, it flushes the * current buffer and loads the correct one.<p> * * On exit from this routine <code>this.curr == this.hi</code> iff <code>pos</code> * is at or past the end-of-file, which can only happen if the file was * opened in read-only mode. */ @Override public void seek(long pos) throws IOException { if (pos >= this.hi_ || pos < this.lo_) { // seeking outside of current buffer -- flush and read this.flushBuffer(); this.lo_ = pos & BuffMask_; // start at BuffSz boundary this.maxHi_ = this.lo_ + (long) this.buff_.length; if (this.diskPos_ != this.lo_) { super.seek(this.lo_); this.diskPos_ = this.lo_; } int n = this.fillBuffer(); this.hi_ = this.lo_ + (long) n; } else { // seeking inside current buffer -- no read required if (pos < this.curr_) { // if seeking backwards, we must flush to maintain V4 this.flushBuffer(); } } this.curr_ = pos; } /* * Does not maintain V4 (i.e. buffer differs from disk contents if previously written to) * - Assumes no writes were made * @param pos * @throws IOException */ public void seekUnsafe(long pos) throws IOException { if (pos >= this.hi_ || pos < this.lo_) { // seeking outside of current buffer -- flush and read this.flushBuffer(); this.lo_ = pos & BuffMask_; // start at BuffSz boundary this.maxHi_ = this.lo_ + (long) this.buff_.length; if (this.diskPos_ != this.lo_) { super.seek(this.lo_); this.diskPos_ = this.lo_; } int n = this.fillBuffer(); this.hi_ = this.lo_ + (long) n; } this.curr_ = pos; } @Override public long getFilePointer() { return this.curr_; } @Override public long length() throws IOException { return Math.max(this.curr_, super.length()); } @Override public int read() throws IOException { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; if (this.hitEOF_) return -1; // slow path -- read another buffer this.seek(this.curr_); if (this.curr_ == this.hi_) return -1; } byte res = this.buff_[(int) (this.curr_ - this.lo_)]; this.curr_++; return ((int) res) & 0xFF; // convert byte -> int } public byte read1() throws IOException { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; if (this.hitEOF_) return -1; // slow path -- read another buffer this.seek(this.curr_); if (this.curr_ == this.hi_) return -1; } byte res = this.buff_[(int) (this.curr_++ - this.lo_)]; return res; } @Override public int read(byte[] b) throws IOException { return this.read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; if (this.hitEOF_) return -1; // slow path -- read another buffer this.seek(this.curr_); if (this.curr_ == this.hi_) return -1; } len = Math.min(len, (int) (this.hi_ - this.curr_)); int buffOff = (int) (this.curr_ - this.lo_); System.arraycopy(this.buff_, buffOff, b, off, len); this.curr_ += len; return len; } public byte readCurrent() throws IOException { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; if (this.hitEOF_) return -1; // slow path -- read another buffer this.seek(this.curr_); if (this.curr_ == this.hi_) return -1; } byte res = this.buff_[(int) (this.curr_ - this.lo_)]; return res; } public void writeCurrent(byte b) throws IOException { if (this.curr_ >= this.hi_) { if (this.hitEOF_ && this.hi_ < this.maxHi_) { // at EOF -- bump "hi" this.hi_++; } else { // slow path -- write current buffer; read next one this.seek(this.curr_); if (this.curr_ == this.hi_) { // appending to EOF -- bump "hi" this.hi_++; } } } this.buff_[(int) (this.curr_ - this.lo_)] = (byte) b; this.dirty_ = true; } @Override public void write(int b) throws IOException { if (this.curr_ >= this.hi_) { if (this.hitEOF_ && this.hi_ < this.maxHi_) { // at EOF -- bump "hi" this.hi_++; } else { // slow path -- write current buffer; read next one this.seek(this.curr_); if (this.curr_ == this.hi_) { // appending to EOF -- bump "hi" this.hi_++; } } } this.buff_[(int) (this.curr_ - this.lo_)] = (byte) b; this.curr_++; this.dirty_ = true; } @Override public void write(byte[] b) throws IOException { this.write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { int n = this.writeAtMost(b, off, len); off += n; len -= n; this.dirty_ = true; } } /* * Write at most "len" bytes to "b" starting at position "off", and return * the number of bytes written. */ private int writeAtMost(byte[] b, int off, int len) throws IOException { if (this.curr_ >= this.hi_) { if (this.hitEOF_ && this.hi_ < this.maxHi_) { // at EOF -- bump "hi" this.hi_ = this.maxHi_; } else { // slow path -- write current buffer; read next one this.seek(this.curr_); if (this.curr_ == this.hi_) { // appending to EOF -- bump "hi" this.hi_ = this.maxHi_; } } } len = Math.min(len, (int) (this.hi_ - this.curr_)); int buffOff = (int) (this.curr_ - this.lo_); System.arraycopy(b, off, this.buff_, buffOff, len); this.curr_ += len; return len; } }
14,715
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PGZIPThreadLocal.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/PGZIPThreadLocal.java
package cn.nukkit.nbt.stream; public class PGZIPThreadLocal extends ThreadLocal<PGZIPState> { private final PGZIPOutputStream parent; public PGZIPThreadLocal(PGZIPOutputStream parent) { this.parent = parent; } @Override protected PGZIPState initialValue() { return new PGZIPState(parent); } }
337
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
FastByteArrayOutputStream.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/FastByteArrayOutputStream.java
package cn.nukkit.nbt.stream; /* * fastutil: Fast & compact type-specific collections for Java * * Copyright (C) 2003-2011 Sebastiano Vigna * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; /** Simple, fast byte-array output stream that exposes the backing array. * * <P>{@link java.io.ByteArrayOutputStream} is nice, but to get its content you * must generate each time a new object. This doesn't happen here. * * <P>This class will automatically enlarge the backing array, doubling its * size whenever new space is needed. The {@link #reset()} method will * mark the content as empty, but will not decrease the capacity * * @author Sebastiano Vigna */ public class FastByteArrayOutputStream extends OutputStream { public static final long ONEOVERPHI = 106039; /** The array backing the output stream. */ public final static int DEFAULT_INITIAL_CAPACITY = 16; /** The array backing the output stream. */ public byte[] array; /** The number of valid bytes in {@link #array}. */ public int length; /** The current writing position. */ private int position; /** Creates a new array output stream with an initial capacity of {@link #DEFAULT_INITIAL_CAPACITY} bytes. */ public FastByteArrayOutputStream() { this( DEFAULT_INITIAL_CAPACITY ); } /** Creates a new array output stream with a given initial capacity. * * @param initialCapacity the initial length of the backing array. */ public FastByteArrayOutputStream( final int initialCapacity ) { array = new byte[ initialCapacity ]; } /** Creates a new array output stream wrapping a given byte array. * * @param a the byte array to wrap. */ public FastByteArrayOutputStream( final byte[] a ) { array = a; } /** Marks this array output stream as empty. */ public FastByteArrayOutputStream reset() { length = 0; position = 0; return this; } public void write( final int b ) { if ( position == length ) { length++; if ( position == array.length ) array = grow( array, length ); } array[ position++ ] = (byte)b; } public static void ensureOffsetLength( final int arrayLength, final int offset, final int length ) { if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( length < 0 ) throw new IllegalArgumentException( "Length (" + length + ") is negative" ); if ( offset + length > arrayLength ) throw new ArrayIndexOutOfBoundsException( "Last index (" + ( offset + length ) + ") is greater than array length (" + arrayLength + ")" ); } public static byte[] grow( final byte[] array, final int length ) { if ( length > array.length ) { final int newLength = (int)Math.min( Math.max( ( ONEOVERPHI * array.length ) >>> 16, length ), Integer.MAX_VALUE ); final byte t[] = new byte[ newLength ]; System.arraycopy( array, 0, t, 0, array.length ); return t; } return array; } public static byte[] grow( final byte[] array, final int length, final int preserve ) { if ( length > array.length ) { final int newLength = (int)Math.min( Math.max( ( ONEOVERPHI * array.length ) >>> 16, length ), Integer.MAX_VALUE ); final byte t[] = new byte[ newLength ]; System.arraycopy( array, 0, t, 0, preserve ); return t; } return array; } public void write( final byte[] b, final int off, final int len ) throws IOException { if ( position + len > array.length ) array = grow( array, position + len, position ); System.arraycopy( b, off, array, position, len ); if ( position + len > length ) length = position += len; } public void position( long newPosition ) { if ( position > Integer.MAX_VALUE ) throw new IllegalArgumentException( "Position too large: " + newPosition ); position = (int)newPosition; } public long position() { return position; } public long length() throws IOException { return length; } public byte[] toByteArray() { if (position == array.length) return array; return Arrays.copyOfRange(array, 0, position); } }
5,198
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
NBTInputStream.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/nbt/stream/NBTInputStream.java
package cn.nukkit.nbt.stream; import cn.nukkit.utils.VarInt; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; /** * author: MagicDroidX * Nukkit Project */ public class NBTInputStream implements DataInput, AutoCloseable { private final DataInputStream stream; private final ByteOrder endianness; private final boolean network; public NBTInputStream(InputStream stream) { this(stream, ByteOrder.BIG_ENDIAN); } public NBTInputStream(InputStream stream, ByteOrder endianness) { this(stream, endianness, false); } public NBTInputStream(InputStream stream, ByteOrder endianness, boolean network) { this.stream = stream instanceof DataInputStream ? (DataInputStream) stream : new DataInputStream(stream); this.endianness = endianness; this.network = network; } public ByteOrder getEndianness() { return endianness; } public boolean isNetwork() { return network; } @Override public void readFully(byte[] b) throws IOException { this.stream.readFully(b); } @Override public void readFully(byte[] b, int off, int len) throws IOException { this.stream.readFully(b, off, len); } @Override public int skipBytes(int n) throws IOException { return this.stream.skipBytes(n); } @Override public boolean readBoolean() throws IOException { return this.stream.readBoolean(); } @Override public byte readByte() throws IOException { return this.stream.readByte(); } @Override public int readUnsignedByte() throws IOException { return this.stream.readUnsignedByte(); } @Override public short readShort() throws IOException { short s = this.stream.readShort(); if (endianness == ByteOrder.LITTLE_ENDIAN) { s = Short.reverseBytes(s); } return s; } @Override public int readUnsignedShort() throws IOException { int s = this.stream.readUnsignedShort(); if (endianness == ByteOrder.LITTLE_ENDIAN) { s = Integer.reverseBytes(s) >> 16; } return s; } @Override public char readChar() throws IOException { char c = this.stream.readChar(); if (endianness == ByteOrder.LITTLE_ENDIAN) { c = Character.reverseBytes(c); } return c; } @Override public int readInt() throws IOException { if (network) { return VarInt.readVarInt(this.stream); } int i = this.stream.readInt(); if (endianness == ByteOrder.LITTLE_ENDIAN) { i = Integer.reverseBytes(i); } return i; } @Override public long readLong() throws IOException { if (network) { return VarInt.readVarLong(this.stream); } long l = this.stream.readLong(); if (endianness == ByteOrder.LITTLE_ENDIAN) { l = Long.reverseBytes(l); } return l; } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(this.readInt()); } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(this.readLong()); } @Override @Deprecated public String readLine() throws IOException { return this.stream.readLine(); } @Override public String readUTF() throws IOException { int length = (int) (network ? VarInt.readUnsignedVarInt(stream) : this.readUnsignedShort()); byte[] bytes = new byte[length]; this.stream.read(bytes); return new String(bytes, StandardCharsets.UTF_8); } public int available() throws IOException { return this.stream.available(); } @Override public void close() throws IOException { this.stream.close(); } }
4,049
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
InventoryType.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/InventoryType.java
package cn.nukkit.inventory; /** * author: MagicDroidX * Nukkit Project */ public enum InventoryType { CHEST(27, "Chest", 0), ENDER_CHEST(27, "Ender Chest", 0), DOUBLE_CHEST(27 + 27, "Double Chest", 0), PLAYER(40, "Player", -1), //36 CONTAINER, 4 ARMOR FURNACE(3, "Furnace", 2), CRAFTING(5, "Crafting", 1), //4 CRAFTING slots, 1 RESULT WORKBENCH(10, "Crafting", 1), //9 CRAFTING slots, 1 RESULT BREWING_STAND(5, "Brewing", 4), //1 INPUT, 3 POTION, 1 fuel ANVIL(3, "Anvil", 5), //2 INPUT, 1 OUTPUT ENCHANT_TABLE(2, "Enchant", 3), //1 INPUT/OUTPUT, 1 LAPIS DISPENSER(0, "Dispenser", 6), //9 CONTAINER DROPPER(9, "Dropper", 7), //9 CONTAINER HOPPER(5, "Hopper", 8), //5 CONTAINER CURSOR(1, "Cursor", -1); private final int size; private final String title; private final int typeId; InventoryType(int defaultSize, String defaultBlockEntity, int typeId) { this.size = defaultSize; this.title = defaultBlockEntity; this.typeId = typeId; } public int getDefaultSize() { return size; } public String getDefaultTitle() { return title; } public int getNetworkType() { return typeId; } }
1,235
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BigCraftingGrid.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/BigCraftingGrid.java
package cn.nukkit.inventory; /** * @author CreeperFace */ public class BigCraftingGrid extends CraftingGrid { public BigCraftingGrid(InventoryHolder holder) { super(holder, 9); } @Override public int getSize() { return 9; } }
267
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
FurnaceInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/FurnaceInventory.java
package cn.nukkit.inventory; import cn.nukkit.blockentity.BlockEntityFurnace; import cn.nukkit.item.Item; /** * author: MagicDroidX * Nukkit Project */ public class FurnaceInventory extends ContainerInventory { public FurnaceInventory(BlockEntityFurnace furnace) { super(furnace, InventoryType.FURNACE); } @Override public BlockEntityFurnace getHolder() { return (BlockEntityFurnace) this.holder; } public Item getResult() { return this.getItem(2); } public Item getFuel() { return this.getItem(1); } public Item getSmelting() { return this.getItem(0); } public boolean setResult(Item item) { return this.setItem(2, item); } public boolean setFuel(Item item) { return this.setItem(1, item); } public boolean setSmelting(Item item) { return this.setItem(0, item); } @Override public void onSlotChange(int index, Item before, boolean send) { super.onSlotChange(index, before, send); this.getHolder().scheduleUpdate(); } }
1,095
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Inventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/Inventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.item.Item; import java.util.Collection; import java.util.Map; import java.util.Set; /** * author: MagicDroidX * Nukkit Project */ public interface Inventory { int MAX_STACK = 64; int getSize(); int getMaxStackSize(); void setMaxStackSize(int size); String getName(); String getTitle(); Item getItem(int index); default boolean setItem(int index, Item item) { return setItem(index, item, true); } boolean setItem(int index, Item item, boolean send); Item[] addItem(Item... slots); boolean canAddItem(Item item); Item[] removeItem(Item... slots); Map<Integer, Item> getContents(); void setContents(Map<Integer, Item> items); void sendContents(Player player); void sendContents(Player... players); void sendContents(Collection<Player> players); void sendSlot(int index, Player player); void sendSlot(int index, Player... players); void sendSlot(int index, Collection<Player> players); boolean contains(Item item); Map<Integer, Item> all(Item item); default int first(Item item) { return first(item, false); } int first(Item item, boolean exact); int firstEmpty(Item item); void decreaseCount(int slot); void remove(Item item); default boolean clear(int index) { return clear(index, true); } boolean clear(int index, boolean send); void clearAll(); boolean isFull(); boolean isEmpty(); Set<Player> getViewers(); InventoryType getType(); InventoryHolder getHolder(); void onOpen(Player who); boolean open(Player who); void close(Player who); void onClose(Player who); void onSlotChange(int index, Item before, boolean send); }
1,835
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerCursorInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/PlayerCursorInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.network.protocol.InventorySlotPacket; import cn.nukkit.network.protocol.types.ContainerIds; /** * @author CreeperFace */ public class PlayerCursorInventory extends BaseInventory { public PlayerCursorInventory(Player holder) { super(holder, InventoryType.CURSOR); } public String getName() { return "Cursor"; } public int getSize() { return 1; } public void setSize(int size) { throw new RuntimeException("Cursor can only carry one item at a time"); } public void sendSlot(int index, Player... target) { InventorySlotPacket pk = new InventorySlotPacket(); pk.slot = index; pk.item = this.getItem(index); for (Player p : target) { if (p == this.getHolder()) { pk.inventoryId = ContainerIds.CURSOR; p.dataPacket(pk); } else { int id; if ((id = p.getWindowId(this)) == ContainerIds.NONE) { this.close(p); continue; } pk.inventoryId = id; p.dataPacket(pk); } } } /** * This override is here for documentation and code completion purposes only. * * @return Player */ public Player getHolder() { return (Player) this.holder; } }
1,445
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
FakeBlockMenu.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/FakeBlockMenu.java
package cn.nukkit.inventory; import cn.nukkit.level.Position; /** * author: MagicDroidX * Nukkit Project */ public class FakeBlockMenu extends Position implements InventoryHolder { private final Inventory inventory; public FakeBlockMenu(Inventory inventory, Position pos) { super(pos.x, pos.y, pos.z, pos.level); this.inventory = inventory; } @Override public Inventory getInventory() { return inventory; } }
465
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
InventoryHolder.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/InventoryHolder.java
package cn.nukkit.inventory; /** * author: MagicDroidX * Nukkit Project */ public interface InventoryHolder { Inventory getInventory(); }
147
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CraftingGrid.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/CraftingGrid.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.utils.MainLogger; import java.util.HashMap; /** * author: MagicDroidX * Nukkit Project */ public class CraftingGrid extends BaseInventory { public CraftingGrid(InventoryHolder holder) { this(holder, 4); } public CraftingGrid(InventoryHolder holder, int overrideSize) { super(holder, InventoryType.CRAFTING, new HashMap<>(), overrideSize); } @Override public int getSize() { return 4; } public void setSize(int size) { throw new RuntimeException("Cannot change the size of a crafting grid"); } public String getName() { return "Crafting"; } public void removeFromAll(Item item) { int count = item.getCount(); for (int i = 0; i < this.size; i++) { Item target = this.getItem(i); if (target.equals(item, true, false)) { count--; target.count--; this.setItem(i, target); if (count <= 0) break; } } if (count != 0) { MainLogger.getLogger().debug("Unexpected ingredient count (" + count + ") in crafting grid"); } } public void sendSlot(int index, Player... target) { //we can't send a inventorySlot of a client-sided inventory window } public void sendContents(Player... target) { //we can't send the contents of a client-sided inventory window } }
1,536
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Fuel.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/Fuel.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; import java.util.Map; import java.util.TreeMap; /** * author: MagicDroidX * Nukkit Project */ public abstract class Fuel { public static final Map<Integer, Short> duration = new TreeMap<>(); static { duration.put(Item.COAL, (short) 1600); duration.put(Item.COAL_BLOCK, (short) 16000); duration.put(Item.TRUNK, (short) 300); duration.put(Item.WOODEN_PLANKS, (short) 300); duration.put(Item.SAPLING, (short) 100); duration.put(Item.WOODEN_AXE, (short) 200); duration.put(Item.WOODEN_PICKAXE, (short) 200); duration.put(Item.WOODEN_SWORD, (short) 200); duration.put(Item.WOODEN_SHOVEL, (short) 200); duration.put(Item.WOODEN_HOE, (short) 200); duration.put(Item.STICK, (short) 100); duration.put(Item.FENCE, (short) 300); duration.put(Item.FENCE_GATE, (short) 300); duration.put(Item.FENCE_GATE_SPRUCE, (short) 300); duration.put(Item.FENCE_GATE_BIRCH, (short) 300); duration.put(Item.FENCE_GATE_JUNGLE, (short) 300); duration.put(Item.FENCE_GATE_ACACIA, (short) 300); duration.put(Item.FENCE_GATE_DARK_OAK, (short) 300); duration.put(Item.WOODEN_STAIRS, (short) 300); duration.put(Item.SPRUCE_WOOD_STAIRS, (short) 300); duration.put(Item.BIRCH_WOOD_STAIRS, (short) 300); duration.put(Item.JUNGLE_WOOD_STAIRS, (short) 300); duration.put(Item.TRAPDOOR, (short) 300); duration.put(Item.WORKBENCH, (short) 300); duration.put(Item.BOOKSHELF, (short) 300); duration.put(Item.CHEST, (short) 300); duration.put(Item.BUCKET, (short) 20000); } }
1,726
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CraftingRecipe.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/CraftingRecipe.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; import java.util.List; import java.util.UUID; /** * @author CreeperFace */ public interface CraftingRecipe extends Recipe { UUID getId(); void setId(UUID id); boolean requiresCraftingTable(); List<Item> getExtraResults(); List<Item> getAllResults(); /** * Returns whether the specified list of crafting grid inputs and outputs matches this recipe. Outputs DO NOT * include the primary result item. * * @param input 2D array of items taken from the crafting grid * @param output 2D array of items put back into the crafting grid (secondary results) * @return bool */ boolean matchItems(Item[][] input, Item[][] output); }
753
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Recipe.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/Recipe.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; /** * author: MagicDroidX * Nukkit Project */ public interface Recipe { Item getResult(); void registerToCraftingManager(CraftingManager manager); }
221
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ContainerInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/ContainerInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.math.NukkitMath; import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.ContainerClosePacket; import cn.nukkit.network.protocol.ContainerOpenPacket; import java.util.Map; /** * author: MagicDroidX * Nukkit Project */ public abstract class ContainerInventory extends BaseInventory { public ContainerInventory(InventoryHolder holder, InventoryType type) { super(holder, type); } public ContainerInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items) { super(holder, type, items); } public ContainerInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items, Integer overrideSize) { super(holder, type, items, overrideSize); } public ContainerInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items, Integer overrideSize, String overrideTitle) { super(holder, type, items, overrideSize, overrideTitle); } @Override public void onOpen(Player who) { super.onOpen(who); ContainerOpenPacket pk = new ContainerOpenPacket(); pk.windowId = who.getWindowId(this); pk.type = this.getType().getNetworkType(); InventoryHolder holder = this.getHolder(); if (holder instanceof Vector3) { pk.x = (int) ((Vector3) holder).getX(); pk.y = (int) ((Vector3) holder).getY(); pk.z = (int) ((Vector3) holder).getZ(); } else { pk.x = pk.y = pk.z = 0; } who.dataPacket(pk); this.sendContents(who); } @Override public void onClose(Player who) { ContainerClosePacket pk = new ContainerClosePacket(); pk.windowId = who.getWindowId(this); who.dataPacket(pk); super.onClose(who); } public static int calculateRedstone(Inventory inv) { if (inv == null) { return 0; } else { int itemCount = 0; float averageCount = 0; for (int slot = 0; slot < inv.getSize(); ++slot) { Item item = inv.getItem(slot); if (item.getId() != 0) { averageCount += (float) item.getCount() / (float) Math.min(inv.getMaxStackSize(), item.getMaxStackSize()); ++itemCount; } } averageCount = averageCount / (float) inv.getSize(); return NukkitMath.floorFloat(averageCount * 14) + (itemCount > 0 ? 1 : 0); } } }
2,595
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
EnchantInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/EnchantInventory.java
package cn.nukkit.inventory; import cn.nukkit.item.enchantment.EnchantmentEntry; import cn.nukkit.level.Position; import java.util.Random; /** * author: MagicDroidX * Nukkit Project */ public class EnchantInventory extends ContainerInventory { private final Random random = new Random(); private int bookshelfAmount = 0; private int[] levels = null; private EnchantmentEntry[] entries = null; public EnchantInventory(Position position) { super(null, InventoryType.ENCHANT_TABLE); this.holder = new FakeBlockMenu(this, position); } @Override public FakeBlockMenu getHolder() { return (FakeBlockMenu) this.holder; } /*@Override //TODO: server side enchant public void onOpen(Player who) { super.onOpen(who); if (this.levels == null) { this.levels = new int[3]; this.bookshelfAmount = this.countBookshelf(); if (this.bookshelfAmount < 0) { this.bookshelfAmount = 0; } if (this.bookshelfAmount > 15) { this.bookshelfAmount = 15; } NukkitRandom random = new NukkitRandom(); double base = (double) random.nextRange(1, 8) + (bookshelfAmount / 2d) + (double) random.nextRange(0, bookshelfAmount); this.levels[0] = (int) Math.max(base / 3, 1); this.levels[1] = (int) ((base * 2) / 3 + 1); this.levels[2] = (int) Math.max(base, bookshelfAmount * 2); } } @Override public void onSlotChange(int index, Item before, boolean send) { super.onSlotChange(index, before, send); if (index == 0) { Item item = this.getItem(0); if (item.getId() == Item.AIR) { this.entries = null; } else if (before.getId() == Item.AIR && !item.hasEnchantments()) { //before enchant if (this.entries == null) { int enchantAbility = item.getEnchantAbility(); this.entries = new EnchantmentEntry[3]; for (int i = 0; i < 3; i++) { ArrayList<Enchantment> result = new ArrayList<>(); int level = this.levels[i]; int k = level; k += ThreadLocalRandom.current().nextInt(0, Math.round(enchantAbility / 2f)); k += ThreadLocalRandom.current().nextInt(0, Math.round(enchantAbility / 2f)); k++; float bonus = (ThreadLocalRandom.current().nextFloat() + ThreadLocalRandom.current().nextFloat() - 1) * 0.15f + 1; int modifiedLevel = (int) (k * (1 + bonus) + 0.5f); ArrayList<Enchantment> possible = new ArrayList<>(); for (Enchantment enchantment : Enchantment.getEnchantments()) { if (enchantment.canEnchant(item)) { for (int enchLevel = enchantment.getMinLevel(); enchLevel < enchantment.getMaxLevel(); enchLevel++) { if (modifiedLevel >= enchantment.getMinEnchantAbility(enchLevel) && modifiedLevel <= enchantment.getMaxEnchantAbility(enchLevel)) { enchantment.setLevel(enchLevel); possible.add(enchantment); } } } } int[] weights = new int[possible.size()]; int total = 0; for (int j = 0; j < weights.length; j++) { int weight = possible.get(j).getWeight(); weights[j] = weight; total += weight; } int v = ThreadLocalRandom.current().nextInt(total + 1); int sum = 0; int key; for (key = 0; key < weights.length; ++key) { sum += weights[key]; if (sum >= v) { key++; break; } } key--; Enchantment enchantment = possible.get(key); result.add(enchantment); possible.remove(key); //Extra enchantment while (!possible.isEmpty()) { modifiedLevel = Math.round(modifiedLevel / 2f); v = ThreadLocalRandom.current().nextInt(0, 51); if (v <= (modifiedLevel + 1)) { for (Enchantment e : new ArrayList<>(possible)) { if (!e.isCompatibleWith(enchantment)) { possible.remove(e); } } weights = new int[possible.size()]; total = 0; for (int j = 0; j < weights.length; j++) { int weight = possible.get(j).getWeight(); weights[j] = weight; total += weight; } v = ThreadLocalRandom.current().nextInt(total + 1); sum = 0; for (key = 0; key < weights.length; ++key) { sum += weights[key]; if (sum >= v) { key++; break; } } key--; enchantment = possible.get(key); result.add(enchantment); possible.remove(key); } else { break; } } this.entries[i] = new EnchantmentEntry(result.stream().toArray(Enchantment[]::new), level, Enchantment.getRandomName()); } } this.sendEnchantmentList(); } } } @Override public void onClose(Player who) { super.onClose(who); for (int i = 0; i < 2; ++i) { this.getHolder().getLevel().dropItem(this.getHolder().add(0.5, 0.5, 0.5), this.getItem(i)); this.clear(i); } if (this.getViewers().size() == 0) { this.levels = null; this.entries = null; this.bookshelfAmount = 0; } } public void onEnchant(Player who, Item before, Item after) { Item result = (before.getId() == Item.BOOK) ? new ItemBookEnchanted() : before; if (!before.hasEnchantments() && after.hasEnchantments() && after.getId() == result.getId() && this.levels != null && this.entries != null) { Enchantment[] enchantments = after.getEnchantments(); for (int i = 0; i < 3; i++) { if (Arrays.equals(enchantments, this.entries[i].getEnchantments())) { Item lapis = this.getItem(1); int level = who.getExperienceLevel(); int exp = who.getExperience(); int cost = this.entries[i].getCost(); if (lapis.getId() == Item.DYE && lapis.getDamage() == DyeColor.BLUE.getDyeData() && lapis.getCount() > i && level >= cost) { result.addEnchantment(enchantments); this.setItem(0, result); lapis.setCount(lapis.getCount() - i - 1); this.setItem(1, lapis); who.setExperience(exp, level - cost); break; } } } } } public int countBookshelf() { int count = 0; Location loc = this.getHolder().getLocation(); Level level = loc.getLevel(); for (int y = 0; y <= 1; y++) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { if (z == 0 && x == 0) continue; if (level.getBlock(loc.add(x, 0, z)).isTransparent()) { if (level.getBlock(loc.add(0, 1, 0)).isTransparent()) { //diagonal and straight if (level.getBlock(loc.add(x << 1, y, z << 1)).getId() == Block.BOOKSHELF) { count++; } if (x != 0 && z != 0) { //one block diagonal and one straight if (level.getBlock(loc.add(x << 1, y, z)).getId() == Block.BOOKSHELF) { ++count; } if (level.getBlock(loc.add(x, y, z << 1)).getId() == Block.BOOKSHELF) { ++count; } } } } } } } return count; } public void sendEnchantmentList() { CraftingDataPacket pk = new CraftingDataPacket(); if (this.entries != null && this.levels != null) { EnchantmentList list = new EnchantmentList(this.entries.length); for (int i = 0; i < list.getSize(); i++) { list.setSlot(i, this.entries[i]); } pk.addEnchantList(list); } //Server.broadcastPacket(this.getViewers(), pk); //TODO: fix this, causes crash in 1.2 }*/ /*@Override public void sendSlot(int index, Player... players) { } @Override public void sendContents(Player... players) { } @Override public boolean setItem(int index, Item item, boolean send) { return super.setItem(index, item, false); }*/ }
10,489
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
FurnaceRecipe.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/FurnaceRecipe.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; /** * author: MagicDroidX * Nukkit Project */ public class FurnaceRecipe implements Recipe { private final Item output; private Item ingredient; public FurnaceRecipe(Item result, Item ingredient) { this.output = result.clone(); this.ingredient = ingredient.clone(); } public void setInput(Item item) { this.ingredient = item.clone(); } public Item getInput() { return this.ingredient.clone(); } @Override public Item getResult() { return this.output.clone(); } @Override public void registerToCraftingManager(CraftingManager manager) { manager.registerFurnaceRecipe(this); } }
750
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerEnderChestInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/PlayerEnderChestInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.block.BlockEnderChest; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.EntityHumanType; import cn.nukkit.level.Level; import cn.nukkit.level.Sound; import cn.nukkit.network.protocol.BlockEventPacket; import cn.nukkit.network.protocol.ContainerClosePacket; import cn.nukkit.network.protocol.ContainerOpenPacket; public class PlayerEnderChestInventory extends BaseInventory { public PlayerEnderChestInventory(EntityHumanType player) { super(player, InventoryType.ENDER_CHEST); } @Override public EntityHuman getHolder() { return (EntityHuman) this.holder; } @Override public void onOpen(Player who) { if (who != this.getHolder()) { return; } super.onOpen(who); ContainerOpenPacket containerOpenPacket = new ContainerOpenPacket(); containerOpenPacket.windowId = who.getWindowId(this); containerOpenPacket.type = this.getType().getNetworkType(); BlockEnderChest chest = who.getViewingEnderChest(); if (chest != null) { containerOpenPacket.x = (int) chest.getX(); containerOpenPacket.y = (int) chest.getY(); containerOpenPacket.z = (int) chest.getZ(); } else { containerOpenPacket.x = containerOpenPacket.y = containerOpenPacket.z = 0; } who.dataPacket(containerOpenPacket); this.sendContents(who); if (chest != null && chest.getViewers().size() == 1) { BlockEventPacket blockEventPacket = new BlockEventPacket(); blockEventPacket.x = (int) chest.getX(); blockEventPacket.y = (int) chest.getY(); blockEventPacket.z = (int) chest.getZ(); blockEventPacket.case1 = 1; blockEventPacket.case2 = 2; Level level = this.getHolder().getLevel(); if (level != null) { level.addSound(this.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTOPEN); level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, blockEventPacket); } } } @Override public void onClose(Player who) { ContainerClosePacket containerClosePacket = new ContainerClosePacket(); containerClosePacket.windowId = who.getWindowId(this); who.dataPacket(containerClosePacket); super.onClose(who); BlockEnderChest chest = who.getViewingEnderChest(); if (chest != null && chest.getViewers().size() == 1) { BlockEventPacket blockEventPacket = new BlockEventPacket(); blockEventPacket.x = (int) chest.getX(); blockEventPacket.y = (int) chest.getY(); blockEventPacket.z = (int) chest.getZ(); blockEventPacket.case1 = 1; blockEventPacket.case2 = 0; Level level = this.getHolder().getLevel(); if (level != null) { level.addSound(this.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTCLOSED); level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, blockEventPacket); } who.setViewingEnderChest(null); } super.onClose(who); } }
3,323
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CustomInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/CustomInventory.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; import java.util.Map; /** * author: MagicDroidX * Nukkit Project */ public abstract class CustomInventory extends ContainerInventory { public CustomInventory(InventoryHolder holder, InventoryType type) { super(holder, type); } public CustomInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items) { super(holder, type, items); } public CustomInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items, Integer overrideSize) { super(holder, type, items, overrideSize); } public CustomInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items, Integer overrideSize, String overrideTitle) { super(holder, type, items, overrideSize, overrideTitle); } }
843
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BaseInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/BaseInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.BlockAir; import cn.nukkit.entity.Entity; import cn.nukkit.event.entity.EntityInventoryChangeEvent; import cn.nukkit.event.inventory.InventoryOpenEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.network.protocol.InventoryContentPacket; import cn.nukkit.network.protocol.InventorySlotPacket; import java.util.*; /** * author: MagicDroidX * Nukkit Project */ public abstract class BaseInventory implements Inventory { protected final InventoryType type; protected int maxStackSize = Inventory.MAX_STACK; protected int size; protected final String name; protected final String title; public final Map<Integer, Item> slots = new HashMap<>(); protected final Set<Player> viewers = new HashSet<>(); protected InventoryHolder holder; public BaseInventory(InventoryHolder holder, InventoryType type) { this(holder, type, new HashMap<>()); } public BaseInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items) { this(holder, type, items, null); } public BaseInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items, Integer overrideSize) { this(holder, type, items, overrideSize, null); } public BaseInventory(InventoryHolder holder, InventoryType type, Map<Integer, Item> items, Integer overrideSize, String overrideTitle) { this.holder = holder; this.type = type; if (overrideSize != null) { this.size = overrideSize; } else { this.size = this.type.getDefaultSize(); } if (overrideTitle != null) { this.title = overrideTitle; } else { this.title = this.type.getDefaultTitle(); } this.name = this.type.getDefaultTitle(); if (!(this instanceof DoubleChestInventory)) { this.setContents(items); } } @Override public int getSize() { return size; } public void setSize(int size) { this.size = size; } @Override public int getMaxStackSize() { return maxStackSize; } @Override public String getName() { return name; } @Override public String getTitle() { return title; } @Override public Item getItem(int index) { return this.slots.containsKey(index) ? this.slots.get(index).clone() : new ItemBlock(new BlockAir(), null, 0); } @Override public Map<Integer, Item> getContents() { return new HashMap<>(this.slots); } @Override public void setContents(Map<Integer, Item> items) { if (items.size() > this.size) { TreeMap<Integer, Item> newItems = new TreeMap<>(); for (Map.Entry<Integer, Item> entry : items.entrySet()) { newItems.put(entry.getKey(), entry.getValue()); } items = newItems; newItems = new TreeMap<>(); int i = 0; for (Map.Entry<Integer, Item> entry : items.entrySet()) { newItems.put(entry.getKey(), entry.getValue()); i++; if (i >= this.size) { break; } } items = newItems; } for (int i = 0; i < this.size; ++i) { if (!items.containsKey(i)) { if (this.slots.containsKey(i)) { this.clear(i); } } else { if (!this.setItem(i, items.get(i))) { this.clear(i); } } } } @Override public boolean setItem(int index, Item item, boolean send) { item = item.clone(); if (index < 0 || index >= this.size) { return false; } else if (item.getId() == 0 || item.getCount() <= 0) { return this.clear(index); } InventoryHolder holder = this.getHolder(); if (holder instanceof Entity) { EntityInventoryChangeEvent ev = new EntityInventoryChangeEvent((Entity) holder, this.getItem(index), item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled()) { this.sendSlot(index, this.getViewers()); return false; } item = ev.getNewItem(); } Item old = this.getItem(index); this.slots.put(index, item.clone()); this.onSlotChange(index, old, send); return true; } @Override public boolean contains(Item item) { int count = Math.max(1, item.getCount()); boolean checkDamage = item.hasMeta() && item.getDamage() >= 0; boolean checkTag = item.getCompoundTag() != null; for (Item i : this.getContents().values()) { if (item.equals(i, checkDamage, checkTag)) { count -= i.getCount(); if (count <= 0) { return true; } } } return false; } @Override public Map<Integer, Item> all(Item item) { Map<Integer, Item> slots = new HashMap<>(); boolean checkDamage = item.hasMeta() && item.getDamage() >= 0; boolean checkTag = item.getCompoundTag() != null; for (Map.Entry<Integer, Item> entry : this.getContents().entrySet()) { if (item.equals(entry.getValue(), checkDamage, checkTag)) { slots.put(entry.getKey(), entry.getValue()); } } return slots; } @Override public void remove(Item item) { boolean checkDamage = item.hasMeta(); boolean checkTag = item.getCompoundTag() != null; for (Map.Entry<Integer, Item> entry : this.getContents().entrySet()) { if (item.equals(entry.getValue(), checkDamage, checkTag)) { this.clear(entry.getKey()); } } } @Override public int first(Item item, boolean exact) { int count = Math.max(1, item.getCount()); boolean checkDamage = item.hasMeta(); boolean checkTag = item.getCompoundTag() != null; for (Map.Entry<Integer, Item> entry : this.getContents().entrySet()) { if (item.equals(entry.getValue(), checkDamage, checkTag) && (entry.getValue().getCount() == count || (!exact && entry.getValue().getCount() > count))) { return entry.getKey(); } } return -1; } @Override public int firstEmpty(Item item) { for (int i = 0; i < this.size; ++i) { if (this.getItem(i).getId() == Item.AIR) { return i; } } return -1; } @Override public void decreaseCount(int slot) { Item item = this.getItem(slot); if (item.getCount() > 0) { item.count--; this.setItem(slot, item); } } @Override public boolean canAddItem(Item item) { item = item.clone(); boolean checkDamage = item.hasMeta(); boolean checkTag = item.getCompoundTag() != null; for (int i = 0; i < this.getSize(); ++i) { Item slot = this.getItem(i); if (item.equals(slot, checkDamage, checkTag)) { int diff; if ((diff = slot.getMaxStackSize() - slot.getCount()) > 0) { item.setCount(item.getCount() - diff); } } else if (slot.getId() == Item.AIR) { item.setCount(item.getCount() - this.getMaxStackSize()); } if (item.getCount() <= 0) { return true; } } return false; } @Override public Item[] addItem(Item... slots) { List<Item> itemSlots = new ArrayList<>(); for (Item slot : slots) { if (slot.getId() != 0 && slot.getCount() > 0) { itemSlots.add(slot.clone()); } } List<Integer> emptySlots = new ArrayList<>(); for (int i = 0; i < this.getSize(); ++i) { Item item = this.getItem(i); if (item.getId() == Item.AIR || item.getCount() <= 0) { emptySlots.add(i); } for (Item slot : new ArrayList<>(itemSlots)) { if (slot.equals(item) && item.getCount() < item.getMaxStackSize()) { int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); if (amount > 0) { slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() + amount); this.setItem(i, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } if (itemSlots.isEmpty()) { break; } } if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { for (int slotIndex : emptySlots) { if (!itemSlots.isEmpty()) { Item slot = itemSlots.get(0); int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); slot.setCount(slot.getCount() - amount); Item item = slot.clone(); item.setCount(amount); this.setItem(slotIndex, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } return itemSlots.stream().toArray(Item[]::new); } @Override public Item[] removeItem(Item... slots) { List<Item> itemSlots = new ArrayList<>(); for (Item slot : slots) { if (slot.getId() != 0 && slot.getCount() > 0) { itemSlots.add(slot.clone()); } } for (int i = 0; i < this.size; ++i) { Item item = this.getItem(i); if (item.getId() == Item.AIR || item.getCount() <= 0) { continue; } for (Item slot : new ArrayList<>(itemSlots)) { if (slot.equals(item, item.hasMeta(), item.getCompoundTag() != null)) { int amount = Math.min(item.getCount(), slot.getCount()); slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() - amount); this.setItem(i, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } if (itemSlots.size() == 0) { break; } } return itemSlots.stream().toArray(Item[]::new); } @Override public boolean clear(int index, boolean send) { if (this.slots.containsKey(index)) { Item item = new ItemBlock(new BlockAir(), null, 0); Item old = this.slots.get(index); InventoryHolder holder = this.getHolder(); if (holder instanceof Entity) { EntityInventoryChangeEvent ev = new EntityInventoryChangeEvent((Entity) holder, old, item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled()) { this.sendSlot(index, this.getViewers()); return false; } item = ev.getNewItem(); } if (item.getId() != Item.AIR) { this.slots.put(index, item.clone()); } else { this.slots.remove(index); } this.onSlotChange(index, old, send); } return true; } @Override public void clearAll() { for (Integer index : this.getContents().keySet()) { this.clear(index); } } @Override public Set<Player> getViewers() { return viewers; } @Override public InventoryHolder getHolder() { return holder; } @Override public void setMaxStackSize(int maxStackSize) { this.maxStackSize = maxStackSize; } @Override public boolean open(Player who) { InventoryOpenEvent ev = new InventoryOpenEvent(this, who); who.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { return false; } this.onOpen(who); return true; } @Override public void close(Player who) { this.onClose(who); } @Override public void onOpen(Player who) { this.viewers.add(who); } @Override public void onClose(Player who) { this.viewers.remove(who); } @Override public void onSlotChange(int index, Item before, boolean send) { if (send) { this.sendSlot(index, this.getViewers()); } } @Override public void sendContents(Player player) { this.sendContents(new Player[]{player}); } @Override public void sendContents(Player... players) { InventoryContentPacket pk = new InventoryContentPacket(); pk.slots = new Item[this.getSize()]; for (int i = 0; i < this.getSize(); ++i) { pk.slots[i] = this.getItem(i); } for (Player player : players) { int id = player.getWindowId(this); if (id == -1 || !player.spawned) { this.close(player); continue; } pk.inventoryId = id; player.dataPacket(pk); } } @Override public boolean isFull() { if (this.slots.size() < this.getSize()) { return false; } for (Item item : this.slots.values()) { if (item == null || item.getId() == 0 || item.getCount() < item.getMaxStackSize() || item.getCount() < this.getMaxStackSize()) { return false; } } return true; } @Override public boolean isEmpty() { if (this.getMaxStackSize() <= 0) { return false; } for (Item item : this.slots.values()) { if (item != null && item.getId() != 0 && item.getCount() > 0) { return false; } } return true; } public int getFreeSpace(Item item) { int maxStackSize = Math.min(item.getMaxStackSize(), this.getMaxStackSize()); int space = (this.getSize() - this.slots.size()) * maxStackSize; for (Item slot : this.getContents().values()) { if (slot == null || slot.getId() == 0) { space += maxStackSize; continue; } if (slot.equals(item, true, true)) { space += maxStackSize - slot.getCount(); } } return space; } @Override public void sendContents(Collection<Player> players) { this.sendContents(players.stream().toArray(Player[]::new)); } @Override public void sendSlot(int index, Player player) { this.sendSlot(index, new Player[]{player}); } @Override public void sendSlot(int index, Player... players) { InventorySlotPacket pk = new InventorySlotPacket(); pk.slot = index; pk.item = this.getItem(index).clone(); for (Player player : players) { int id = player.getWindowId(this); if (id == -1) { this.close(player); continue; } pk.inventoryId = id; player.dataPacket(pk); } } @Override public void sendSlot(int index, Collection<Player> players) { this.sendSlot(index, players.stream().toArray(Player[]::new)); } @Override public InventoryType getType() { return type; } }
16,255
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
HopperInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/HopperInventory.java
package cn.nukkit.inventory; import cn.nukkit.blockentity.BlockEntityHopper; /** * Created by CreeperFace on 8.5.2017. */ public class HopperInventory extends ContainerInventory { public HopperInventory(BlockEntityHopper hopper) { super(hopper, InventoryType.HOPPER); } @Override public BlockEntityHopper getHolder() { return (BlockEntityHopper) super.getHolder(); } }
411
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ChestInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/ChestInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.blockentity.BlockEntityChest; import cn.nukkit.level.Level; import cn.nukkit.level.Sound; import cn.nukkit.network.protocol.BlockEventPacket; /** * author: MagicDroidX * Nukkit Project */ public class ChestInventory extends ContainerInventory { public ChestInventory(BlockEntityChest chest) { super(chest, InventoryType.CHEST); } @Override public BlockEntityChest getHolder() { return (BlockEntityChest) this.holder; } @Override public void onOpen(Player who) { super.onOpen(who); if (this.getViewers().size() == 1) { BlockEventPacket pk = new BlockEventPacket(); pk.x = (int) this.getHolder().getX(); pk.y = (int) this.getHolder().getY(); pk.z = (int) this.getHolder().getZ(); pk.case1 = 1; pk.case2 = 2; Level level = this.getHolder().getLevel(); if (level != null) { level.addSound(this.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTOPEN); level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, pk); } } } @Override public void onClose(Player who) { if (this.getViewers().size() == 1) { BlockEventPacket pk = new BlockEventPacket(); pk.x = (int) this.getHolder().getX(); pk.y = (int) this.getHolder().getY(); pk.z = (int) this.getHolder().getZ(); pk.case1 = 1; pk.case2 = 0; Level level = this.getHolder().getLevel(); if (level != null) { level.addSound(this.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTCLOSED); level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, pk); } } super.onClose(who); } }
1,961
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BrewingRecipe.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/BrewingRecipe.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; public class BrewingRecipe implements Recipe { private final Item output; private final Item potion; private Item ingredient; public BrewingRecipe(Item result, Item ingredient, Item potion) { this.output = result.clone(); this.ingredient = ingredient.clone(); this.potion = potion.clone(); } public void setInput(Item item) { ingredient = item.clone(); } public Item getInput() { return ingredient.clone(); } public Item getPotion() { return potion.clone(); } @Override public Item getResult() { return output.clone(); } @Override public void registerToCraftingManager(CraftingManager manager) { manager.registerBrewingRecipe(this); } }
837
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
AnvilInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/AnvilInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.Position; import cn.nukkit.level.Sound; import java.util.ArrayList; import java.util.Arrays; /** * author: MagicDroidX * Nukkit Project */ public class AnvilInventory extends ContainerInventory { public static final int TARGET = 0; public static final int SACRIFICE = 1; public static final int RESULT = 2; public AnvilInventory(Position position) { super(null, InventoryType.ANVIL); this.holder = new FakeBlockMenu(this, position); } @Override public FakeBlockMenu getHolder() { return (FakeBlockMenu) this.holder; } public boolean onRename(Player player, Item resultItem) { Item local = getItem(TARGET); Item second = getItem(SACRIFICE); if (!resultItem.equals(local, true, false) || resultItem.getCount() != local.getCount()) { //Item does not match target item. Everything must match except the tags. return false; } if (local.equals(resultItem)) { //just item transaction return true; } if (local.getId() != 0 && second.getId() == 0) { //only rename local.setCustomName(resultItem.getCustomName()); setItem(RESULT, local); player.getInventory().addItem(local); clearAll(); player.getInventory().sendContents(player); sendContents(player); player.getLevel().addSound(player, Sound.RANDOM_ANVIL_USE); return true; } else if (local.getId() != 0 && second.getId() != 0) { //enchants combining if (!local.equals(second, true, false)) { return false; } if (local.getId() != 0 && second.getId() != 0) { Item result = local.clone(); int enchants = 0; ArrayList<Enchantment> enchantments = new ArrayList<>(Arrays.asList(second.getEnchantments())); ArrayList<Enchantment> baseEnchants = new ArrayList<>(); for (Enchantment ench : local.getEnchantments()) { if (ench.isMajor()) { baseEnchants.add(ench); } } for (Enchantment enchantment : enchantments) { if (enchantment.getLevel() < 0 || enchantment.getId() < 0) { continue; } if (enchantment.isMajor()) { boolean same = false; boolean another = false; for (Enchantment baseEnchant : baseEnchants) { if (baseEnchant.getId() == enchantment.getId()) same = true; else { another = true; } } if (!same && another) { continue; } } Enchantment localEnchantment = local.getEnchantment(enchantment.getId()); if (localEnchantment != null) { int level = Math.max(localEnchantment.getLevel(), enchantment.getLevel()); if (localEnchantment.getLevel() == enchantment.getLevel()) level++; enchantment.setLevel(level); result.addEnchantment(enchantment); continue; } result.addEnchantment(enchantment); enchants++; } result.setCustomName(resultItem.getCustomName()); player.getInventory().addItem(result); player.getInventory().sendContents(player); clearAll(); sendContents(player); player.getLevel().addSound(player, Sound.RANDOM_ANVIL_USE); return true; } } return false; } @Override public void onClose(Player who) { super.onClose(who); who.craftingType = Player.CRAFTING_SMALL; who.resetCraftingGridType(); for (int i = 0; i < 2; ++i) { this.getHolder().getLevel().dropItem(this.getHolder().add(0.5, 0.5, 0.5), this.getItem(i)); this.clear(i); } } @Override public void onOpen(Player who) { super.onOpen(who); who.craftingType = Player.CRAFTING_ANVIL; } /*@Override public boolean setItem(int index, Item item, boolean send) { return super.setItem(index, item, false); } @Override public void sendSlot(int index, Player... players) { } @Override public void sendContents(Player... player) { }*/ }
4,998
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BrewingInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/BrewingInventory.java
package cn.nukkit.inventory; import cn.nukkit.blockentity.BlockEntityBrewingStand; import cn.nukkit.item.Item; public class BrewingInventory extends ContainerInventory { public BrewingInventory(BlockEntityBrewingStand brewingStand) { super(brewingStand, InventoryType.BREWING_STAND); } @Override public BlockEntityBrewingStand getHolder() { return (BlockEntityBrewingStand) this.holder; } public Item getIngredient() { return getItem(0); } public void setIngredient(Item item) { setItem(0, item); } public void setFuel(Item fuel) { setItem(4, fuel); } public Item getFuel() { return getItem(4); } @Override public void onSlotChange(int index, Item before, boolean send) { super.onSlotChange(index, before, send); if (index >= 0 && index <= 2) { this.getHolder().updateBlock(); } this.getHolder().scheduleUpdate(); } }
984
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CraftingManager.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/CraftingManager.java
package cn.nukkit.inventory; import cn.nukkit.Server; import cn.nukkit.item.Item; import cn.nukkit.item.ItemPotion; import cn.nukkit.network.protocol.CraftingDataPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.utils.BinaryStream; import cn.nukkit.utils.Config; import cn.nukkit.utils.MainLogger; import cn.nukkit.utils.Utils; import io.netty.util.collection.CharObjectHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import java.io.File; import java.io.IOException; import java.util.*; import java.util.zip.Deflater; /** * author: MagicDroidX * Nukkit Project */ public class CraftingManager { public final Collection<Recipe> recipes = new ArrayDeque<>(); protected final Map<Integer, Map<String, ShapedRecipe>> shapedRecipes = new Int2ObjectOpenHashMap<>(); protected final Map<Integer, Map<String, ShapelessRecipe>> shapelessRecipes = new Int2ObjectOpenHashMap<>(); public final Map<Integer, FurnaceRecipe> furnaceRecipes = new Int2ObjectOpenHashMap<>(); public final Map<Integer, BrewingRecipe> brewingRecipes = new Int2ObjectOpenHashMap<>(); private static int RECIPE_COUNT = 0; public static DataPacket packet = null; private static final Comparator<Item> recipeComparator = (i1, i2) -> { if (i1.getId() > i2.getId()) { return 1; } else if (i1.getId() < i2.getId()) { return -1; } else if (i1.getDamage() > i2.getDamage()) { return 1; } else if (i1.getDamage() < i2.getDamage()) { return -1; } else if (i1.getCount() > i2.getCount()) { return 1; } else if (i1.getCount() < i2.getCount()) { return -1; } else { return 0; } }; @SuppressWarnings("unchecked") public CraftingManager() { String path = Server.getInstance().getDataPath() + "recipes.json"; if (!new File(path).exists()) { try { Utils.writeFile(path, Server.class.getClassLoader().getResourceAsStream("recipes.json")); } catch (IOException e) { MainLogger.getLogger().logException(e); } } List<Map> recipes = new Config(path, Config.JSON).getMapList("recipes"); MainLogger.getLogger().info("Loading recipes..."); for (Map<String, Object> recipe : recipes) { try { switch (Utils.toInt(recipe.get("type"))) { case 0: // TODO: handle multiple result items Map<String, Object> first = ((List<Map>) recipe.get("output")).get(0); ShapelessRecipe result = new ShapelessRecipe(Item.fromJson(first)); for (Map<String, Object> ingredient : ((List<Map>) recipe.get("input"))) { result.addIngredient(Item.fromJson(ingredient)); } this.registerRecipe(result); break; case 1: List<Map> output = (List<Map>) recipe.get("output"); first = output.remove(0); String[] shape = ((List<String>) recipe.get("shape")).stream().toArray(String[]::new); Map<Character, Item> ingredients = new CharObjectHashMap<>(); List<Item> extraResults = new ArrayList<>(); Map<String, Map<String, Object>> input = (Map) recipe.get("input"); for (Map.Entry<String, Map<String, Object>> ingredientEntry : input.entrySet()) { char ingredientChar = ingredientEntry.getKey().charAt(0); Item ingredient = Item.fromJson(ingredientEntry.getValue()); ingredients.put(ingredientChar, ingredient); } for (Map<String, Object> data : output) { extraResults.add(Item.fromJson(data)); } this.registerRecipe(new ShapedRecipe(Item.fromJson(first), shape, ingredients, extraResults)); break; case 2: case 3: Map<String, Object> resultMap = (Map) recipe.get("output"); Item resultItem = Item.fromJson(resultMap); this.registerRecipe(new FurnaceRecipe(resultItem, Item.get(Utils.toInt(recipe.get("inputId")), recipe.containsKey("inputDamage") ? Utils.toInt(recipe.get("inputDamage")) : -1, 1))); break; default: break; } } catch (Exception e) { MainLogger.getLogger().error("Exception during registering recipe", e); } } this.registerBrewing(); this.rebuildPacket(); MainLogger.getLogger().info("Loaded " + this.recipes.size() + " recipes."); } protected void registerBrewing() { registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.AWKWARD, 1), Item.get(Item.NETHER_WART, 0, 1), Item.get(Item.POTION, ItemPotion.NO_EFFECTS, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.THICK, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.NO_EFFECTS, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.MUNDANE_II, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.NO_EFFECTS, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.STRENGTH, 1), Item.get(Item.BLAZE_POWDER, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.STRENGTH_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.STRENGTH, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.STRENGTH_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.STRENGTH_II, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.STRENGTH_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.STRENGTH, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.STRENGTH_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.STRENGTH_LONG, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.WEAKNESS, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.NO_EFFECTS, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.WEAKNESS_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.WEAKNESS, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.NIGHT_VISION, 1), Item.get(Item.GOLDEN_CARROT, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.NIGHT_VISION_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.NIGHT_VISION, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.INVISIBLE, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.NIGHT_VISION, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.INVISIBLE_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.INVISIBLE, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.INVISIBLE_LONG, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.NIGHT_VISION_LONG, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.FIRE_RESISTANCE, 1), Item.get(Item.MAGMA_CREAM, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.FIRE_RESISTANCE_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.FIRE_RESISTANCE, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SLOWNESS, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.FIRE_RESISTANCE, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SLOWNESS, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.SPEED, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SLOWNESS, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.LEAPING, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SLOWNESS_LONG, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.FIRE_RESISTANCE_LONG, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SLOWNESS_LONG, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.SPEED_LONG, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SPEED, 1), Item.get(Item.SUGAR, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SPEED_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.SPEED, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.SPEED_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.SPEED, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.INSTANT_HEALTH, 1), Item.get(Item.GLISTERING_MELON, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.INSTANT_HEALTH_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.INSTANT_HEALTH, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.POISON, 1), Item.get(Item.SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.POISON_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.POISON, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.POISON_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.POISON, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.REGENERATION, 1), Item.get(Item.GHAST_TEAR, 0, 1), Item.get(Item.POTION, ItemPotion.AWKWARD, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.REGENERATION_LONG, 1), Item.get(Item.REDSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.REGENERATION, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.REGENERATION_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.REGENERATION, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.HARMING, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.WATER_BREATHING, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.HARMING, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.INSTANT_HEALTH, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.HARMING, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.POISON, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.HARMING_II, 1), Item.get(Item.GLOWSTONE_DUST, 0, 1), Item.get(Item.POTION, ItemPotion.HARMING, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.HARMING_II, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.INSTANT_HEALTH_II, 1))); registerBrewingRecipe(new BrewingRecipe(Item.get(Item.POTION, ItemPotion.HARMING_II, 1), Item.get(Item.FERMENTED_SPIDER_EYE, 0, 1), Item.get(Item.POTION, ItemPotion.POISON_LONG, 1))); } public void rebuildPacket() { CraftingDataPacket pk = new CraftingDataPacket(); pk.cleanRecipes = true; for (Recipe recipe : this.getRecipes()) { if (recipe instanceof ShapedRecipe) { pk.addShapedRecipe((ShapedRecipe) recipe); } else if (recipe instanceof ShapelessRecipe) { pk.addShapelessRecipe((ShapelessRecipe) recipe); } } for (FurnaceRecipe recipe : this.getFurnaceRecipes().values()) { pk.addFurnaceRecipe(recipe); } pk.encode(); packet = pk.compress(Deflater.BEST_COMPRESSION); } public Collection<Recipe> getRecipes() { return recipes; } public Map<Integer, FurnaceRecipe> getFurnaceRecipes() { return furnaceRecipes; } public FurnaceRecipe matchFurnaceRecipe(Item input) { FurnaceRecipe recipe = this.furnaceRecipes.get(getItemHash(input)); if (recipe == null) recipe = this.furnaceRecipes.get(getItemHash(input.getId(), 0)); return recipe; } public void registerShapedRecipe(ShapedRecipe recipe) { int resultHash = getItemHash(recipe.getResult()); Map<String, ShapedRecipe> map = shapedRecipes.get(resultHash); if (map == null) { map = new HashMap<>(); shapedRecipes.put(resultHash, map); } String inputHash = getMultiItemHash(recipe.getIngredientList()); map.put(inputHash, recipe); } private String getMultiItemHash(Collection<Item> items) { BinaryStream stream = new BinaryStream(); for (Item item : items) { stream.putUnsignedVarInt(item.getId()); stream.putVarInt(item.getDamage()); } return new String(stream.getByteArray()); } public void registerShapelessRecipe(ShapelessRecipe recipe) { List<Item> list = recipe.getIngredientList(); Collections.sort(list, recipeComparator); String inputHash = getMultiItemHash(list); int resultHash = getItemHash(recipe.getResult()); Map<String, ShapelessRecipe> map = shapelessRecipes.get(resultHash); if (map == null) { map = new HashMap<>(); shapelessRecipes.put(resultHash, map); } map.put(inputHash, recipe); } public void registerFurnaceRecipe(FurnaceRecipe recipe) { Item input = recipe.getInput(); this.furnaceRecipes.put(getItemHash(input), recipe); } public void registerBrewingRecipe(BrewingRecipe recipe) { Item input = recipe.getInput(); Item potion = recipe.getPotion(); this.brewingRecipes.put(getItemHash(input.getId(), (!potion.hasMeta() ? 0 : potion.getDamage())), recipe); } public BrewingRecipe matchBrewingRecipe(Item input, Item potion) { return brewingRecipes.get(getItemHash(input.getId(), (!potion.hasMeta() ? 0 : potion.getDamage()))); } public CraftingRecipe matchRecipe(Item[][] inputMap, Item primaryOutput, Item[][] extraOutputMap) { //TODO: try to match special recipes before anything else (first they need to be implemented!) int outputHash = getItemHash(primaryOutput); if (this.shapedRecipes.containsKey(outputHash)) { int numItems = 0; for (Item[] items : inputMap) for (Item item : items) numItems++; List<Item> itemCol = new ArrayList<>(numItems); for (Item[] items : inputMap) for (Item item : items) itemCol.add(item); String inputHash = getMultiItemHash(itemCol); Map<String, ShapedRecipe> recipeMap = shapedRecipes.get(outputHash); if (recipeMap != null) { ShapedRecipe recipe = recipeMap.get(inputHash); if (recipe != null && recipe.matchItems(this.cloneItemMap(inputMap), this.cloneItemMap(extraOutputMap))) { //matched a recipe by hash return recipe; } for (ShapedRecipe shapedRecipe : recipeMap.values()) { if (shapedRecipe.matchItems(this.cloneItemMap(inputMap), this.cloneItemMap(extraOutputMap))) { return shapedRecipe; } } } } if (shapelessRecipes.containsKey(outputHash)) { List<Item> list = new ArrayList<>(); for (Item[] a : inputMap) { list.addAll(Arrays.asList(a)); } list.sort(recipeComparator); String inputHash = getMultiItemHash(list); Map<String, ShapelessRecipe> recipes = shapelessRecipes.get(outputHash); if (recipes == null) { return null; } ShapelessRecipe recipe = recipes.get(inputHash); if (recipe != null && recipe.matchItems(this.cloneItemMap(inputMap), this.cloneItemMap(extraOutputMap))) { return recipe; } for (ShapelessRecipe shapelessRecipe : recipes.values()) { if (shapelessRecipe.matchItems(this.cloneItemMap(inputMap), this.cloneItemMap(extraOutputMap))) { return shapelessRecipe; } } } return null; } private Item[][] cloneItemMap(Item[][] map) { Item[][] newMap = new Item[map.length][]; for (int i = 0; i < newMap.length; i++) { Item[] old = map[i]; Item[] n = new Item[old.length]; System.arraycopy(old, 0, n, 0, n.length); newMap[i] = n; } for (int y = 0; y < newMap.length; y++) { Item[] row = newMap[y]; for (int x = 0; x < row.length; x++) { Item item = newMap[y][x]; newMap[y][x] = item.clone(); } } return newMap; } public void registerRecipe(Recipe recipe) { if (recipe instanceof CraftingRecipe) { UUID id = Utils.dataToUUID(String.valueOf(++RECIPE_COUNT), String.valueOf(recipe.getResult().getId()), String.valueOf(recipe.getResult().getDamage()), String.valueOf(recipe.getResult().getCount()), Arrays.toString(recipe.getResult().getCompoundTag())); ((CraftingRecipe) recipe).setId(id); this.recipes.add(recipe); } recipe.registerToCraftingManager(this); } private static int getItemHash(Item item) { return getItemHash(item.getId(), item.hasMeta() ? item.getDamage() : 0); } private static int getItemHash(int id, int meta) { return id + (meta << 9); } public static class Entry { final int resultItemId; final int resultMeta; final int ingredientItemId; final int ingredientMeta; final String recipeShape; final int resultAmount; public Entry(int resultItemId, int resultMeta, int ingredientItemId, int ingredientMeta, String recipeShape, int resultAmount) { this.resultItemId = resultItemId; this.resultMeta = resultMeta; this.ingredientItemId = ingredientItemId; this.ingredientMeta = ingredientMeta; this.recipeShape = recipeShape; this.resultAmount = resultAmount; } } }
19,689
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/PlayerInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.BlockAir; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.EntityHumanType; import cn.nukkit.event.entity.EntityArmorChangeEvent; import cn.nukkit.event.entity.EntityInventoryChangeEvent; import cn.nukkit.event.player.PlayerItemHeldEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.network.protocol.InventoryContentPacket; import cn.nukkit.network.protocol.InventorySlotPacket; import cn.nukkit.network.protocol.MobArmorEquipmentPacket; import cn.nukkit.network.protocol.MobEquipmentPacket; import cn.nukkit.network.protocol.types.ContainerIds; import java.util.Collection; /** * author: MagicDroidX * Nukkit Project */ public class PlayerInventory extends BaseInventory { protected int itemInHandIndex = 0; private int[] hotbar; public PlayerInventory(EntityHumanType player) { super(player, InventoryType.PLAYER); this.hotbar = new int[this.getHotbarSize()]; for (int i = 0; i < this.hotbar.length; i++) { this.hotbar[i] = i; } } @Override public int getSize() { return super.getSize() - 4; } @Override public void setSize(int size) { super.setSize(size + 4); this.sendContents(this.getViewers()); } /** * Called when a client equips a hotbar inventorySlot. This method should not be used by plugins. * This method will call PlayerItemHeldEvent. * * @param slot hotbar slot Number of the hotbar slot to equip. * @return boolean if the equipment change was successful, false if not. */ public boolean equipItem(int slot) { if (!isHotbarSlot(slot)) { this.sendContents((Player) this.getHolder()); return false; } if (this.getHolder() instanceof Player) { PlayerItemHeldEvent ev = new PlayerItemHeldEvent((Player) this.getHolder(), this.getItem(slot), slot); this.getHolder().getLevel().getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { this.sendContents(this.getViewers()); return false; } } this.setHeldItemIndex(slot, false); return true; } private boolean isHotbarSlot(int slot) { return slot >= 0 && slot <= this.getHotbarSize(); } @Deprecated public int getHotbarSlotIndex(int index) { return index; } @Deprecated public void setHotbarSlotIndex(int index, int slot) { } public int getHeldItemIndex() { return this.itemInHandIndex; } public void setHeldItemIndex(int index) { setHeldItemIndex(index, true); } public void setHeldItemIndex(int index, boolean send) { if (index >= 0 && index < this.getHotbarSize()) { this.itemInHandIndex = index; if (this.getHolder() instanceof Player && send) { this.sendHeldItem((Player) this.getHolder()); } this.sendHeldItem(this.getHolder().getViewers().values()); } } public Item getItemInHand() { Item item = this.getItem(this.getHeldItemIndex()); if (item != null) { return item; } else { return new ItemBlock(new BlockAir(), 0, 0); } } public boolean setItemInHand(Item item) { return this.setItem(this.getHeldItemIndex(), item); } @Deprecated public int getHeldItemSlot() { return this.itemInHandIndex; } public void setHeldItemSlot(int slot) { if (!isHotbarSlot(slot)) { return; } this.itemInHandIndex = slot; if (this.getHolder() instanceof Player) { this.sendHeldItem((Player) this.getHolder()); } this.sendHeldItem(this.getViewers()); } public void sendHeldItem(Player... players) { Item item = this.getItemInHand(); MobEquipmentPacket pk = new MobEquipmentPacket(); pk.item = item; pk.inventorySlot = pk.hotbarSlot = this.getHeldItemIndex(); for (Player player : players) { pk.eid = this.getHolder().getId(); if (player.equals(this.getHolder())) { pk.eid = player.getId(); this.sendSlot(this.getHeldItemIndex(), player); } player.dataPacket(pk); } } public void sendHeldItem(Collection<Player> players) { this.sendHeldItem(players.stream().toArray(Player[]::new)); } @Override public void onSlotChange(int index, Item before, boolean send) { EntityHuman holder = this.getHolder(); if (holder instanceof Player && !((Player) holder).spawned) { return; } if (index >= this.getSize()) { this.sendArmorSlot(index, this.getViewers()); this.sendArmorSlot(index, this.getHolder().getViewers().values()); } else { super.onSlotChange(index, before, send); } } public int getHotbarSize() { return 9; } public Item getArmorItem(int index) { return this.getItem(this.getSize() + index); } public boolean setArmorItem(int index, Item item) { return this.setArmorItem(index, item, false); } public boolean setArmorItem(int index, Item item, boolean ignoreArmorEvents) { return this.setItem(this.getSize() + index, item, ignoreArmorEvents); } public Item getHelmet() { return this.getItem(this.getSize()); } public Item getChestplate() { return this.getItem(this.getSize() + 1); } public Item getLeggings() { return this.getItem(this.getSize() + 2); } public Item getBoots() { return this.getItem(this.getSize() + 3); } public boolean setHelmet(Item helmet) { return this.setItem(this.getSize(), helmet); } public boolean setChestplate(Item chestplate) { return this.setItem(this.getSize() + 1, chestplate); } public boolean setLeggings(Item leggings) { return this.setItem(this.getSize() + 2, leggings); } public boolean setBoots(Item boots) { return this.setItem(this.getSize() + 3, boots); } @Override public boolean setItem(int index, Item item) { return setItem(index, item, true, false); } private boolean setItem(int index, Item item, boolean send, boolean ignoreArmorEvents) { if (index < 0 || index >= this.size) { return false; } else if (item.getId() == 0 || item.getCount() <= 0) { return this.clear(index); } //Armor change if (!ignoreArmorEvents && index >= this.getSize()) { EntityArmorChangeEvent ev = new EntityArmorChangeEvent(this.getHolder(), this.getItem(index), item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled() && this.getHolder() != null) { this.sendArmorSlot(index, this.getViewers()); return false; } item = ev.getNewItem(); } else { EntityInventoryChangeEvent ev = new EntityInventoryChangeEvent(this.getHolder(), this.getItem(index), item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled()) { this.sendSlot(index, this.getViewers()); return false; } item = ev.getNewItem(); } Item old = this.getItem(index); this.slots.put(index, item.clone()); this.onSlotChange(index, old, send); return true; } @Override public boolean clear(int index, boolean send) { if (this.slots.containsKey(index)) { Item item = new ItemBlock(new BlockAir(), null, 0); Item old = this.slots.get(index); if (index >= this.getSize() && index < this.size) { EntityArmorChangeEvent ev = new EntityArmorChangeEvent(this.getHolder(), old, item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled()) { if (index >= this.size) { this.sendArmorSlot(index, this.getViewers()); } else { this.sendSlot(index, this.getViewers()); } return false; } item = ev.getNewItem(); } else { EntityInventoryChangeEvent ev = new EntityInventoryChangeEvent(this.getHolder(), old, item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled()) { if (index >= this.size) { this.sendArmorSlot(index, this.getViewers()); } else { this.sendSlot(index, this.getViewers()); } return false; } item = ev.getNewItem(); } if (item.getId() != Item.AIR) { this.slots.put(index, item.clone()); } else { this.slots.remove(index); } this.onSlotChange(index, old, send); } return true; } public Item[] getArmorContents() { Item[] armor = new Item[4]; for (int i = 0; i < 4; i++) { armor[i] = this.getItem(this.getSize() + i); } return armor; } @Override public void clearAll() { int limit = this.getSize() + 4; for (int index = 0; index < limit; ++index) { this.clear(index); } } public void sendArmorContents(Player player) { this.sendArmorContents(new Player[]{player}); } public void sendArmorContents(Player[] players) { Item[] armor = this.getArmorContents(); MobArmorEquipmentPacket pk = new MobArmorEquipmentPacket(); pk.eid = this.getHolder().getId(); pk.slots = armor; pk.encode(); pk.isEncoded = true; for (Player player : players) { if (player.equals(this.getHolder())) { InventoryContentPacket pk2 = new InventoryContentPacket(); pk2.inventoryId = InventoryContentPacket.SPECIAL_ARMOR; pk2.slots = armor; player.dataPacket(pk2); } else { player.dataPacket(pk); } } } public void setArmorContents(Item[] items) { if (items.length < 4) { Item[] newItems = new Item[4]; System.arraycopy(items, 0, newItems, 0, items.length); items = newItems; } for (int i = 0; i < 4; ++i) { if (items[i] == null) { items[i] = new ItemBlock(new BlockAir(), null, 0); } if (items[i].getId() == Item.AIR) { this.clear(this.getSize() + i); } else { this.setItem(this.getSize() + i, items[i]); } } } public void sendArmorContents(Collection<Player> players) { this.sendArmorContents(players.stream().toArray(Player[]::new)); } public void sendArmorSlot(int index, Player player) { this.sendArmorSlot(index, new Player[]{player}); } public void sendArmorSlot(int index, Player[] players) { Item[] armor = this.getArmorContents(); MobArmorEquipmentPacket pk = new MobArmorEquipmentPacket(); pk.eid = this.getHolder().getId(); pk.slots = armor; pk.encode(); pk.isEncoded = true; for (Player player : players) { if (player.equals(this.getHolder())) { InventorySlotPacket pk2 = new InventorySlotPacket(); pk2.inventoryId = InventoryContentPacket.SPECIAL_ARMOR; pk2.slot = index - this.getSize(); pk2.item = this.getItem(index); player.dataPacket(pk2); } else { player.dataPacket(pk); } } } public void sendArmorSlot(int index, Collection<Player> players) { this.sendArmorSlot(index, players.stream().toArray(Player[]::new)); } @Override public void sendContents(Player player) { this.sendContents(new Player[]{player}); } @Override public void sendContents(Collection<Player> players) { this.sendContents(players.stream().toArray(Player[]::new)); } @Override public void sendContents(Player[] players) { InventoryContentPacket pk = new InventoryContentPacket(); pk.slots = new Item[this.getSize()]; for (int i = 0; i < this.getSize(); ++i) { pk.slots[i] = this.getItem(i); } /*//Because PE is stupid and shows 9 less slots than you send it, give it 9 dummy slots so it shows all the REAL slots. for(int i = this.getSize(); i < this.getSize() + this.getHotbarSize(); ++i){ pk.slots[i] = new ItemBlock(new BlockAir()); } pk.slots[i] = new ItemBlock(new BlockAir()); }*/ for (Player player : players) { int id = player.getWindowId(this); if (id == -1 || !player.spawned) { this.close(player); continue; } pk.inventoryId = id; player.dataPacket(pk.clone()); } } @Override public void sendSlot(int index, Player player) { this.sendSlot(index, new Player[]{player}); } @Override public void sendSlot(int index, Collection<Player> players) { this.sendSlot(index, players.stream().toArray(Player[]::new)); } @Override public void sendSlot(int index, Player... players) { InventorySlotPacket pk = new InventorySlotPacket(); pk.slot = index; pk.item = this.getItem(index).clone(); for (Player player : players) { if (player.equals(this.getHolder())) { pk.inventoryId = ContainerIds.INVENTORY; player.dataPacket(pk); } else { int id = player.getWindowId(this); if (id == -1) { this.close(player); continue; } pk.inventoryId = id; player.dataPacket(pk.clone()); } } } public void sendCreativeContents() { if (!(this.getHolder() instanceof Player)) { return; } Player p = (Player) this.getHolder(); InventoryContentPacket pk = new InventoryContentPacket(); pk.inventoryId = ContainerIds.CREATIVE; if (!p.isSpectator()) { //fill it for all gamemodes except spectator pk.slots = Item.getCreativeItems().stream().toArray(Item[]::new); } p.dataPacket(pk); } @Override public EntityHuman getHolder() { return (EntityHuman) super.getHolder(); } }
15,212
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
DoubleChestInventory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/DoubleChestInventory.java
package cn.nukkit.inventory; import cn.nukkit.Player; import cn.nukkit.blockentity.BlockEntityChest; import cn.nukkit.item.Item; import cn.nukkit.level.Level; import cn.nukkit.level.Sound; import cn.nukkit.network.protocol.BlockEventPacket; import java.util.HashMap; import java.util.Map; /** * author: MagicDroidX * Nukkit Project */ public class DoubleChestInventory extends ContainerInventory implements InventoryHolder { private final ChestInventory left; private final ChestInventory right; public DoubleChestInventory(BlockEntityChest left, BlockEntityChest right) { super(null, InventoryType.DOUBLE_CHEST); this.holder = this; this.left = left.getRealInventory(); this.right = right.getRealInventory(); Map<Integer, Item> items = new HashMap<>(); // First we add the items from the left chest for (int idx = 0; idx < this.left.getSize(); idx++) { if (this.left.getContents().containsKey(idx)) { // Don't forget to skip empty slots! items.put(idx, this.left.getContents().get(idx)); } } // And them the items from the right chest for (int idx = 0; idx < this.right.getSize(); idx++) { if (this.right.getContents().containsKey(idx)) { // Don't forget to skip empty slots! items.put(idx + this.left.getSize(), this.right.getContents().get(idx)); // idx + this.left.getSize() so we don't overlap left chest items } } this.setContents(items); } @Override public Inventory getInventory() { return this; } @Override public BlockEntityChest getHolder() { return this.left.getHolder(); } @Override public Item getItem(int index) { return index < this.left.getSize() ? this.left.getItem(index) : this.right.getItem(index - this.right.getSize()); } @Override public boolean setItem(int index, Item item, boolean send) { return index < this.left.getSize() ? this.left.setItem(index, item, send) : this.right.setItem(index - this.right.getSize(), item, send); } @Override public boolean clear(int index) { return index < this.left.getSize() ? this.left.clear(index) : this.right.clear(index - this.right.getSize()); } @Override public Map<Integer, Item> getContents() { Map<Integer, Item> contents = new HashMap<>(); for (int i = 0; i < this.getSize(); ++i) { contents.put(i, this.getItem(i)); } return contents; } @Override public void setContents(Map<Integer, Item> items) { if (items.size() > this.size) { Map<Integer, Item> newItems = new HashMap<>(); for (int i = 0; i < this.size; i++) { newItems.put(i, items.get(i)); } items = newItems; } for (int i = 0; i < this.size; i++) { if (!items.containsKey(i)) { if (i < this.left.size) { if (this.left.slots.containsKey(i)) { this.clear(i); } } else if (this.right.slots.containsKey(i - this.left.size)) { this.clear(i); } } else if (!this.setItem(i, items.get(i))) { this.clear(i); } } } @Override public void onOpen(Player who) { super.onOpen(who); this.left.viewers.add(who); this.right.viewers.add(who); if (this.getViewers().size() == 1) { BlockEventPacket pk1 = new BlockEventPacket(); pk1.x = (int) this.left.getHolder().getX(); pk1.y = (int) this.left.getHolder().getY(); pk1.z = (int) this.left.getHolder().getZ(); pk1.case1 = 1; pk1.case2 = 2; Level level = this.left.getHolder().getLevel(); if (level != null) { level.addSound(this.left.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTOPEN); level.addChunkPacket((int) this.left.getHolder().getX() >> 4, (int) this.left.getHolder().getZ() >> 4, pk1); } BlockEventPacket pk2 = new BlockEventPacket(); pk2.x = (int) this.right.getHolder().getX(); pk2.y = (int) this.right.getHolder().getY(); pk2.z = (int) this.right.getHolder().getZ(); pk2.case1 = 1; pk2.case2 = 2; level = this.right.getHolder().getLevel(); if (level != null) { level.addSound(this.right.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTOPEN); level.addChunkPacket((int) this.right.getHolder().getX() >> 4, (int) this.right.getHolder().getZ() >> 4, pk2); } } } @Override public void onClose(Player who) { if (this.getViewers().size() == 1) { BlockEventPacket pk1 = new BlockEventPacket(); pk1.x = (int) this.right.getHolder().getX(); pk1.y = (int) this.right.getHolder().getY(); pk1.z = (int) this.right.getHolder().getZ(); pk1.case1 = 1; pk1.case2 = 0; Level level = this.right.getHolder().getLevel(); if (level != null) { level.addSound(this.right.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTCLOSED); level.addChunkPacket((int) this.right.getHolder().getX() >> 4, (int) this.right.getHolder().getZ() >> 4, pk1); } BlockEventPacket pk2 = new BlockEventPacket(); pk2.x = (int) this.left.getHolder().getX(); pk2.y = (int) this.left.getHolder().getY(); pk2.z = (int) this.left.getHolder().getZ(); pk2.case1 = 1; pk2.case2 = 0; level = this.left.getHolder().getLevel(); if (level != null) { level.addSound(this.left.getHolder().add(0.5, 0.5, 0.5), Sound.RANDOM_CHESTCLOSED); level.addChunkPacket((int) this.left.getHolder().getX() >> 4, (int) this.left.getHolder().getZ() >> 4, pk2); } } this.left.viewers.remove(who); this.right.viewers.remove(who); super.onClose(who); } public ChestInventory getLeftSide() { return this.left; } public ChestInventory getRightSide() { return this.right; } }
6,440
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ShapelessRecipe.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/ShapelessRecipe.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; /** * author: MagicDroidX * Nukkit Project */ public class ShapelessRecipe implements CraftingRecipe { private final Item output; private long least,most; private final List<Item> ingredients = new ArrayList<>(); public ShapelessRecipe(Item result) { this.output = result.clone(); } @Override public Item getResult() { return this.output.clone(); } @Override public UUID getId() { return new UUID(least, most); } @Override public void setId(UUID uuid) { this.least = uuid.getLeastSignificantBits(); this.most = uuid.getMostSignificantBits(); } public ShapelessRecipe addIngredient(Item item) { if (this.ingredients.size() > 9) { throw new IllegalArgumentException("Shapeless recipes cannot have more than 9 ingredients"); } Item it = item.clone(); it.setCount(1); while (item.getCount() > 0) { this.ingredients.add(it.clone()); item.setCount(item.getCount() - 1); } return this; } public ShapelessRecipe removeIngredient(Item item) { for (Item ingredient : this.ingredients) { if (item.getCount() <= 0) { break; } if (ingredient.equals(item, item.hasMeta(), item.getCompoundTag() != null)) { this.ingredients.remove(ingredient); item.setCount(item.getCount() - 1); } } return this; } public List<Item> getIngredientList() { List<Item> ingredients = new ArrayList<>(); for (Item ingredient : this.ingredients) { ingredients.add(ingredient.clone()); } return ingredients; } public int getIngredientCount() { int count = 0; for (Item ingredient : this.ingredients) { count += ingredient.getCount(); } return count; } @Override public void registerToCraftingManager(CraftingManager manager) { manager.registerShapelessRecipe(this); } @Override public boolean requiresCraftingTable() { return this.ingredients.size() > 4; } @Override public List<Item> getExtraResults() { return null; } @Override public List<Item> getAllResults() { return null; } @Override public boolean matchItems(Item[][] input, Item[][] output) { List<Item> haveInputs = new ArrayList<>(); for (Item[] items : input) { haveInputs.addAll(Arrays.asList(items)); } List<Item> needInputs = this.getIngredientList(); if (!this.matchItemList(haveInputs, needInputs)) { return false; } List<Item> haveOutputs = new ArrayList<>(); for (Item[] items : input) { haveOutputs.addAll(Arrays.asList(items)); } List<Item> needOutputs = this.getExtraResults(); return this.matchItemList(haveOutputs, needOutputs); } private boolean matchItemList(List<Item> haveItems, List<Item> needItems) { for (Item haveItem : new ArrayList<>(haveItems)) { if (haveItem.isNull()) { haveItems.remove(haveItem); continue; } for (Item needItem : new ArrayList<>(needItems)) { if (needItem.equals(haveItem, needItem.hasMeta(), needItem.hasCompoundTag()) && needItem.getCount() == haveItem.getCount()) { haveItems.remove(haveItem); needItems.remove(needItem); break; } } } return haveItems.isEmpty() && haveItems.isEmpty(); } }
3,902
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ShapedRecipe.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/ShapedRecipe.java
package cn.nukkit.inventory; import cn.nukkit.item.Item; import cn.nukkit.utils.Utils; import java.util.*; /** * author: MagicDroidX * Nukkit Project */ public class ShapedRecipe implements CraftingRecipe { private Item primaryResult; private List<Item> extraResults = new ArrayList<>(); private long least,most; private final String[] shape; private final Map<Character, Item> ingredients = new HashMap<>(); /** * Constructs a ShapedRecipe instance. * * @param primaryResult * @param shape<br> Array of 1, 2, or 3 strings representing the rows of the recipe. * This accepts an array of 1, 2 or 3 strings. Each string should be of the same length and must be at most 3 * characters long. Each character represents a unique type of ingredient. Spaces are interpreted as air. * @param ingredients<br> Char => Item map of items to be set into the shape. * This accepts an array of Items, indexed by character. Every unique character (except space) in the shape * array MUST have a corresponding item in this list. Space character is automatically treated as air. * @param extraResults<br> List of additional result items to leave in the crafting grid afterwards. Used for things like cake recipe * empty buckets. * <p> * Note: Recipes **do not** need to be square. Do NOT add padding for empty rows/columns. */ public ShapedRecipe(Item primaryResult, String[] shape, Map<Character, Item> ingredients, List<Item> extraResults) { int rowCount = shape.length; if (rowCount > 3 || rowCount <= 0) { throw new RuntimeException("Shaped recipes may only have 1, 2 or 3 rows, not " + rowCount); } int columnCount = shape[0].length(); if (columnCount > 3 || rowCount <= 0) { throw new RuntimeException("Shaped recipes may only have 1, 2 or 3 columns, not " + columnCount); } //for($shape as $y => $row) { for (int y = 0; y < rowCount; y++) { String row = shape[y]; if (row.length() != columnCount) { throw new RuntimeException("Shaped recipe rows must all have the same length (expected " + columnCount + ", got " + row.length() + ")"); } for (int x = 0; x < columnCount; ++x) { char c = row.charAt(x); if (c != ' ' && !ingredients.containsKey(c)) { throw new RuntimeException("No item specified for symbol '" + c + "'"); } } } this.primaryResult = primaryResult.clone(); this.extraResults.addAll(extraResults); this.shape = shape; for (Map.Entry<Character, Item> entry : ingredients.entrySet()) { this.setIngredient(entry.getKey(), entry.getValue()); } } public int getWidth() { return this.shape[0].length(); } public int getHeight() { return this.shape.length; } @Override public Item getResult() { return this.primaryResult; } @Override public UUID getId() { return new UUID(least, most); } @Override public void setId(UUID uuid) { this.least = uuid.getLeastSignificantBits(); this.most = uuid.getMostSignificantBits(); } public ShapedRecipe setIngredient(String key, Item item) { return this.setIngredient(key.charAt(0), item); } public ShapedRecipe setIngredient(char key, Item item) { if (String.join("", this.shape).indexOf(key) < 0) { throw new RuntimeException("Symbol does not appear in the shape: " + key); } this.ingredients.put(key, item); return this; } public List<Item> getIngredientList() { List<Item> items = new ArrayList<>(); for (int y = 0, y2 = getHeight(); y < y2; ++y) { for (int x = 0, x2 = getWidth(); x < x2; ++x) { items.add(getIngredient(x, y)); } } return items; } public Map<Integer, Map<Integer, Item>> getIngredientMap() { Map<Integer, Map<Integer, Item>> ingredients = new LinkedHashMap<>(); for (int y = 0, y2 = getHeight(); y < y2; ++y) { Map<Integer, Item> m = new LinkedHashMap<>(); for (int x = 0, x2 = getWidth(); x < x2; ++x) { m.put(x, getIngredient(x, y)); } ingredients.put(y, m); } return ingredients; } public Item getIngredient(int x, int y) { Item item = this.ingredients.get(this.shape[y].charAt(x)); return item != null ? item.clone() : Item.get(Item.AIR); } public String[] getShape() { return shape; } @Override public void registerToCraftingManager(CraftingManager manager) { manager.registerShapedRecipe(this); } @Override public List<Item> getExtraResults() { return extraResults; } @Override public List<Item> getAllResults() { List<Item> list = new ArrayList<>(this.extraResults); list.add(primaryResult); return list; } @Override public boolean matchItems(Item[][] input, Item[][] output) { if (!matchInputMap(cloneItemArray(input))) { //Item[][] result = input; /*for(int i = 0; i < input.length; i++) { Item[] origin = input[i]; Item[] dest = new Item[origin.length]; System.arraycopy(origin, 0, dest, 0, dest.length); result[i] = dest; }*/ for (int i = 0; i < input.length; i++) { Item[] old = input[i]; Item[] newArray = new Item[old.length]; System.arraycopy(old, 0, newArray, 0, newArray.length); Utils.reverseArray(newArray); input[i] = newArray; } if (!matchInputMap(input)) { return false; } } //and then, finally, check that the output items are good: List<Item> haveItems = new ArrayList<>(); for (Item[] items : output) { haveItems.addAll(Arrays.asList(items)); } List<Item> needItems = this.getExtraResults(); for (Item haveItem : new ArrayList<>(haveItems)) { if (haveItem.isNull()) { haveItems.remove(haveItem); continue; } for (Item needItem : new ArrayList<>(needItems)) { if (needItem.equals(haveItem, needItem.hasMeta(), needItem.hasCompoundTag()) && needItem.getCount() == haveItem.getCount()) { haveItems.remove(haveItem); needItems.remove(needItem); break; } } } return haveItems.isEmpty() && needItems.isEmpty(); } private boolean matchInputMap(Item[][] input) { Map<Integer, Map<Integer, Item>> map = this.getIngredientMap(); //match the given items to the requested items for (int y = 0, y2 = this.getHeight(); y < y2; ++y) { for (int x = 0, x2 = this.getWidth(); x < x2; ++x) { Item given = input[y][x]; Item required = map.get(y).get(x); if (given == null || !required.equals(given, required.hasMeta(), required.hasCompoundTag()) || required.getCount() != given.getCount()) { return false; } input[y][x] = null; } } //check if there are any items left in the grid outside of the recipe for (Item[] items : input) { for (Item item : items) { if (item != null && !item.isNull()) { return false; } } } return true; } private Item[][] cloneItemArray(Item[][] map) { Item[][] newMap = new Item[map.length][]; for (int i = 0; i < newMap.length; i++) { Item[] old = map[i]; Item[] n = new Item[old.length]; System.arraycopy(old, 0, n, 0, n.length); newMap[i] = n; } return newMap; } @Override public boolean requiresCraftingTable() { return this.getHeight() > 2 || this.getWidth() > 2; } public static class Entry { public final int x; public final int y; public Entry(int x, int y) { this.x = x; this.y = y; } } }
8,746
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CraftingTransaction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/CraftingTransaction.java
package cn.nukkit.inventory.transaction; import cn.nukkit.Player; import cn.nukkit.event.inventory.CraftItemEvent; import cn.nukkit.inventory.BigCraftingGrid; import cn.nukkit.inventory.CraftingRecipe; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.item.Item; import cn.nukkit.math.NukkitMath; import cn.nukkit.network.protocol.ContainerClosePacket; import cn.nukkit.network.protocol.types.ContainerIds; import java.util.Arrays; import java.util.List; /** * @author CreeperFace */ public class CraftingTransaction extends InventoryTransaction { protected int gridSize; protected Item[][] inputs; protected Item[][] secondaryOutputs; protected Item primaryOutput; protected CraftingRecipe recipe; public CraftingTransaction(Player source, List<InventoryAction> actions) { super(source, actions, false); this.gridSize = (source.getCraftingGrid() instanceof BigCraftingGrid) ? 3 : 2; Item air = Item.get(Item.AIR, 0, 1); this.inputs = new Item[gridSize][gridSize]; for (Item[] a : this.inputs) { Arrays.fill(a, air); } this.secondaryOutputs = new Item[gridSize][gridSize]; for (Item[] a : this.secondaryOutputs) { Arrays.fill(a, air); } init(source, actions); } public void setInput(int index, Item item) { int y = NukkitMath.floorDouble((double) index / this.gridSize); int x = index % this.gridSize; if (this.inputs[y][x].isNull()) { inputs[y][x] = item.clone(); } else if (!inputs[y][x].equals(item)) { throw new RuntimeException("Input " + index + " has already been set and does not match the current item (expected " + inputs[y][x] + ", got " + item + ")"); } } public Item[][] getInputMap() { return inputs; } public void setExtraOutput(int index, Item item) { int y = (index / this.gridSize); int x = index % gridSize; if (secondaryOutputs[y][x].isNull()) { secondaryOutputs[y][x] = item.clone(); } else if (!secondaryOutputs[y][x].equals(item)) { throw new RuntimeException("Output " + index + " has already been set and does not match the current item (expected " + secondaryOutputs[y][x] + ", got " + item + ")"); } } public Item getPrimaryOutput() { return primaryOutput; } public void setPrimaryOutput(Item item) { if (primaryOutput == null) { primaryOutput = item.clone(); } else if (!primaryOutput.equals(item)) { throw new RuntimeException("Primary result item has already been set and does not match the current item (expected " + primaryOutput + ", got " + item + ")"); } } public CraftingRecipe getRecipe() { return recipe; } private Item[][] reindexInputs() { int xOffset = gridSize; int yOffset = gridSize; int height = 0; int width = 0; for (int y = 0; y < this.inputs.length; y++) { Item[] row = this.inputs[y]; for (int x = 0; x < row.length; x++) { Item item = row[x]; if (!item.isNull()) { xOffset = Math.min(x, xOffset); yOffset = Math.min(y, yOffset); height = Math.max(y + 1 - yOffset, height); width = Math.max(x + 1 - xOffset, width); } } } if (height == 0 || width == 0) { return new Item[0][]; } Item air = Item.get(Item.AIR, 0, 0); Item[][] reindexed = new Item[height][width]; for (Item[] i : reindexed) { Arrays.fill(i, air); } for (int y = 0; y < reindexed.length; y++) { Item[] row = reindexed[y]; System.arraycopy(this.inputs[y + yOffset], xOffset, reindexed[y], 0, row.length); //hope I converted it right :D /*for (int x = 0; x < row.length; x++) { reindexed[y][x] = this.inputs[y + yOffset][x + xOffset]; }*/ } return reindexed; } public boolean canExecute() { Item[][] inputs = reindexInputs(); recipe = source.getServer().getCraftingManager().matchRecipe(inputs, this.primaryOutput, this.secondaryOutputs); return this.recipe != null && super.canExecute(); } protected boolean callExecuteEvent() { CraftItemEvent ev; this.source.getServer().getPluginManager().callEvent(ev = new CraftItemEvent(this)); return !ev.isCancelled(); } protected void sendInventories() { super.sendInventories(); /* * TODO: HACK! * we can't resend the contents of the crafting window, so we force the client to close it instead. * So people don't whine about messy desync issues when someone cancels CraftItemEvent, or when a crafting * transaction goes wrong. */ ContainerClosePacket pk = new ContainerClosePacket(); pk.windowId = ContainerIds.NONE; this.source.dataPacket(pk); this.source.resetCraftingGridType(); } public boolean execute() { if (super.execute()) { switch (this.primaryOutput.getId()) { case Item.CRAFTING_TABLE: source.awardAchievement("buildWorkBench"); break; case Item.WOODEN_PICKAXE: source.awardAchievement("buildPickaxe"); break; case Item.FURNACE: source.awardAchievement("buildFurnace"); break; case Item.WOODEN_HOE: source.awardAchievement("buildHoe"); break; case Item.BREAD: source.awardAchievement("makeBread"); break; case Item.CAKE: source.awardAchievement("bakeCake"); break; case Item.STONE_PICKAXE: case Item.GOLDEN_PICKAXE: case Item.IRON_PICKAXE: case Item.DIAMOND_PICKAXE: source.awardAchievement("buildBetterPickaxe"); break; case Item.WOODEN_SWORD: source.awardAchievement("buildSword"); break; case Item.DIAMOND: source.awardAchievement("diamond"); break; } return true; } return false; } }
6,645
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
InventoryTransaction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/InventoryTransaction.java
package cn.nukkit.inventory.transaction; import cn.nukkit.Player; import cn.nukkit.event.inventory.InventoryClickEvent; import cn.nukkit.event.inventory.InventoryTransactionEvent; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.item.Item; import cn.nukkit.utils.MainLogger; import java.util.*; import java.util.Map.Entry; /** * @author CreeperFace */ public class InventoryTransaction { private long creationTime; protected boolean hasExecuted; protected Player source; protected Set<Inventory> inventories = new HashSet<>(); protected Set<InventoryAction> actions = new HashSet<>(); public InventoryTransaction(Player source, List<InventoryAction> actions) { this(source, actions, true); } public InventoryTransaction(Player source, List<InventoryAction> actions, boolean init) { if (init) { init(source, actions); } } protected void init(Player source, List<InventoryAction> actions) { creationTime = System.currentTimeMillis(); this.source = source; for (InventoryAction action : actions) { this.addAction(action); } } public Player getSource() { return source; } public long getCreationTime() { return creationTime; } public Set<Inventory> getInventories() { return inventories; } public Set<InventoryAction> getActions() { return actions; } public void addAction(InventoryAction action) { if (!this.actions.contains(action)) { this.actions.add(action); action.onAddToTransaction(this); } else { throw new RuntimeException("Tried to add the same action to a transaction twice"); } } /** * This method should not be used by plugins, it's used to add tracked inventories for InventoryActions * involving inventories. */ public void addInventory(Inventory inventory) { if (!this.inventories.contains(inventory)) { this.inventories.add(inventory); } } protected boolean matchItems(List<Item> needItems, List<Item> haveItems) { for (InventoryAction action : this.actions) { if (action.getTargetItem().getId() != Item.AIR) { needItems.add(action.getTargetItem()); } if (!action.isValid(this.source)) { return false; } if (action.getSourceItem().getId() != Item.AIR) { haveItems.add(action.getSourceItem()); } } for (Item needItem : new ArrayList<>(needItems)) { for (Item haveItem : new ArrayList<>(haveItems)) { if (needItem.equals(haveItem)) { int amount = Math.min(haveItem.getCount(), needItem.getCount()); needItem.setCount(needItem.getCount() - amount); haveItem.setCount(haveItem.getCount() - amount); if (haveItem.getCount() == 0) { haveItems.remove(haveItem); } if (needItem.getCount() == 0) { needItems.remove(needItem); break; } } } } return haveItems.isEmpty() && needItems.isEmpty(); } protected void sendInventories() { for (Inventory inventory : this.inventories) { inventory.sendContents(this.source); if (inventory instanceof PlayerInventory) { ((PlayerInventory) inventory).sendArmorContents(this.source); } } } /** * Iterates over SlotChangeActions in this transaction and compacts any which refer to the same inventorySlot in the same * inventory so they can be correctly handled. * <p> * Under normal circumstances, the same inventorySlot would never be changed more than once in a single transaction. However, * due to the way things like the crafting grid are "implemented" in MCPE 1.2 (a.k.a. hacked-in), we may get * multiple inventorySlot changes referring to the same inventorySlot in a single transaction. These multiples are not even guaranteed * to be in the correct order (inventorySlot splitting in the crafting grid for example, causes the actions to be sent in the * wrong order), so this method also tries to chain them into order. * * @return bool */ protected boolean squashDuplicateSlotChanges() { Map<Integer, List<SlotChangeAction>> slotChanges = new HashMap<>(); for (InventoryAction action : this.actions) { if (action instanceof SlotChangeAction) { int hash = Objects.hash(((SlotChangeAction) action).getInventory(), ((SlotChangeAction) action).getSlot()); List<SlotChangeAction> list = slotChanges.get(hash); if (list == null) { list = new ArrayList<>(); } list.add((SlotChangeAction) action); slotChanges.put(hash, list); } } for (Entry<Integer, List<SlotChangeAction>> entry : new ArrayList<>(slotChanges.entrySet())) { int hash = entry.getKey(); List<SlotChangeAction> list = entry.getValue(); if (list.size() == 1) { //No need to compact inventorySlot changes if there is only one on this inventorySlot slotChanges.remove(hash); continue; } List<SlotChangeAction> originalList = new ArrayList<>(list); SlotChangeAction originalAction = null; Item lastTargetItem = null; for (int i = 0; i < list.size(); i++) { SlotChangeAction action = list.get(i); if (action.isValid(this.source)) { originalAction = action; lastTargetItem = action.getTargetItem(); list.remove(i); break; } } if (originalAction == null) { return false; //Couldn't find any actions that had a source-item matching the current inventory inventorySlot } int sortedThisLoop; do { sortedThisLoop = 0; for (int i = 0; i < list.size(); i++) { SlotChangeAction action = list.get(i); Item actionSource = action.getSourceItem(); if (actionSource.equalsExact(lastTargetItem)) { lastTargetItem = action.getTargetItem(); list.remove(i); sortedThisLoop++; } else if (actionSource.equals(lastTargetItem)) { lastTargetItem.count -= actionSource.count; list.remove(i); if (lastTargetItem.count == 0) sortedThisLoop++; } } } while (sortedThisLoop > 0); if (list.size() > 0) { //couldn't chain all the actions together MainLogger.getLogger().debug("Failed to compact " + originalList.size() + " actions for " + this.source.getName()); return false; } for (SlotChangeAction action : originalList) { this.actions.remove(action); } this.addAction(new SlotChangeAction(originalAction.getInventory(), originalAction.getSlot(), originalAction.getSourceItem(), lastTargetItem)); MainLogger.getLogger().debug("Successfully compacted " + originalList.size() + " actions for " + this.source.getName()); } return true; } public boolean canExecute() { this.squashDuplicateSlotChanges(); List<Item> haveItems = new ArrayList<>(); List<Item> needItems = new ArrayList<>(); return matchItems(needItems, haveItems) && this.actions.size() > 0 && haveItems.size() == 0 && needItems.size() == 0; } protected boolean callExecuteEvent() { InventoryTransactionEvent ev = new InventoryTransactionEvent(this); this.source.getServer().getPluginManager().callEvent(ev); SlotChangeAction from = null; SlotChangeAction to = null; Player who = null; for (InventoryAction action : this.actions) { if (!(action instanceof SlotChangeAction)) { continue; } SlotChangeAction slotChange = (SlotChangeAction) action; if (slotChange.getInventory() instanceof PlayerInventory) { who = (Player) slotChange.getInventory().getHolder(); } if (from == null) { from = slotChange; } else { to = slotChange; } } if (who != null && to != null) { if (from.getTargetItem().getCount() > from.getSourceItem().getCount()) { from = to; } InventoryClickEvent ev2 = new InventoryClickEvent(who, from.getInventory(), from.getSlot(), from.getSourceItem(), from.getTargetItem()); this.source.getServer().getPluginManager().callEvent(ev2); if (ev2.isCancelled()) { return false; } } return !ev.isCancelled(); } public boolean execute() { if (this.hasExecuted() || !this.canExecute()) { this.sendInventories(); return false; } if (!callExecuteEvent()) { this.sendInventories(); return true; } for (InventoryAction action : this.actions) { if (!action.onPreExecute(this.source)) { this.sendInventories(); return true; } } for (InventoryAction action : this.actions) { if (action.execute(this.source)) { action.onExecuteSuccess(this.source); } else { action.onExecuteFail(this.source); } } this.hasExecuted = true; return true; } public boolean hasExecuted() { return this.hasExecuted; } }
10,486
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ReleaseItemData.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/data/ReleaseItemData.java
package cn.nukkit.inventory.transaction.data; import cn.nukkit.item.Item; import cn.nukkit.math.Vector3; /** * @author CreeperFace */ public class ReleaseItemData implements TransactionData { public int actionType; public int hotbarSlot; public Item itemInHand; public Vector3 headRot; }
309
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
UseItemData.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/data/UseItemData.java
package cn.nukkit.inventory.transaction.data; import cn.nukkit.item.Item; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockVector3; import cn.nukkit.math.Vector3; import cn.nukkit.math.Vector3f; /** * @author CreeperFace */ public class UseItemData implements TransactionData { public int actionType; public BlockVector3 blockPos; public BlockFace face; public int hotbarSlot; public Item itemInHand; public Vector3 playerPos; public Vector3f clickPos; }
500
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
UseItemOnEntityData.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/data/UseItemOnEntityData.java
package cn.nukkit.inventory.transaction.data; import cn.nukkit.item.Item; import cn.nukkit.math.Vector3; /** * @author CreeperFace */ public class UseItemOnEntityData implements TransactionData { public long entityRuntimeId; public int actionType; public int hotbarSlot; public Item itemInHand; public Vector3 vector1; public Vector3 vector2; }
375
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TransactionData.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/data/TransactionData.java
package cn.nukkit.inventory.transaction.data; /** * @author CreeperFace */ public interface TransactionData { }
115
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
SlotChangeAction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/action/SlotChangeAction.java
package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.item.Item; import java.util.HashSet; import java.util.Set; /** * @author CreeperFace */ public class SlotChangeAction extends InventoryAction { protected Inventory inventory; private int inventorySlot; public SlotChangeAction(Inventory inventory, int inventorySlot, Item sourceItem, Item targetItem) { super(sourceItem, targetItem); this.inventory = inventory; this.inventorySlot = inventorySlot; } /** * Returns the inventory involved in this action. */ public Inventory getInventory() { return this.inventory; } /** * Returns the inventorySlot in the inventory which this action modified. */ public int getSlot() { return inventorySlot; } /** * Checks if the item in the inventory at the specified inventorySlot is the same as this action's source item. */ public boolean isValid(Player source) { Item check = inventory.getItem(this.inventorySlot); return check.equalsExact(this.sourceItem); } /** * Sets the item into the target inventory. */ public boolean execute(Player source) { return this.inventory.setItem(this.inventorySlot, this.targetItem, false); } /** * Sends inventorySlot changes to other viewers of the inventory. This will not send any change back to the source Player. */ public void onExecuteSuccess(Player source) { Set<Player> viewers = new HashSet<>(this.inventory.getViewers()); viewers.remove(source); this.inventory.sendSlot(this.inventorySlot, viewers); } /** * Sends the original inventorySlot contents to the source player to revert the action. */ public void onExecuteFail(Player source) { this.inventory.sendSlot(this.inventorySlot, source); } @Override public void onAddToTransaction(InventoryTransaction transaction) { transaction.addInventory(this.inventory); } }
2,168
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
DropItemAction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/action/DropItemAction.java
package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; import cn.nukkit.event.player.PlayerDropItemEvent; import cn.nukkit.item.Item; /** * @author CreeperFace */ public class DropItemAction extends InventoryAction { public DropItemAction(Item source, Item target) { super(source, target); } /** * Verifies that the source item of a drop-item action must be air. This is not strictly necessary, just a sanity * check. */ public boolean isValid(Player source) { return this.sourceItem.isNull(); } @Override public boolean onPreExecute(Player source) { PlayerDropItemEvent ev; source.getServer().getPluginManager().callEvent(ev = new PlayerDropItemEvent(source, this.targetItem)); if (ev.isCancelled()) { return false; } return true; } /** * Drops the target item in front of the player. */ public boolean execute(Player source) { return source.dropItem(this.targetItem); } public void onExecuteSuccess(Player source) { } public void onExecuteFail(Player source) { } }
1,159
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CreativeInventoryAction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/action/CreativeInventoryAction.java
package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; import cn.nukkit.item.Item; /** * @author CreeperFace */ public class CreativeInventoryAction extends InventoryAction { /** * Player put an item into the creative window to destroy it. */ public static final int TYPE_DELETE_ITEM = 0; /** * Player took an item from the creative window. */ public static final int TYPE_CREATE_ITEM = 1; protected int actionType; public CreativeInventoryAction(Item source, Item target, int action) { super(source, target); } /** * Checks that the player is in creative, and (if creating an item) that the item exists in the creative inventory. */ public boolean isValid(Player source) { return source.isCreative() && (this.actionType == TYPE_DELETE_ITEM || Item.getCreativeItemIndex(this.sourceItem) != -1); } /** * Returns the type of the action. */ public int getActionType() { return actionType; } /** * No need to do anything extra here: this type just provides a place for items to disappear or appear from. */ public boolean execute(Player source) { return true; } public void onExecuteSuccess(Player source) { } public void onExecuteFail(Player source) { } }
1,362
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CraftingTakeResultAction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTakeResultAction.java
package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; import cn.nukkit.inventory.transaction.CraftingTransaction; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.item.Item; /** * @author CreeperFace */ public class CraftingTakeResultAction extends InventoryAction { public CraftingTakeResultAction(Item sourceItem, Item targetItem) { super(sourceItem, targetItem); } public void onAddToTransaction(InventoryTransaction transaction) { if (transaction instanceof CraftingTransaction) { ((CraftingTransaction) transaction).setPrimaryOutput(this.getSourceItem()); } else { throw new RuntimeException(getClass().getName() + " can only be added to CraftingTransactions"); } } @Override public boolean isValid(Player source) { return true; } @Override public boolean execute(Player source) { return true; } @Override public void onExecuteSuccess(Player $source) { } @Override public void onExecuteFail(Player source) { } }
1,113
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
CraftingTransferMaterialAction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTransferMaterialAction.java
package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; import cn.nukkit.inventory.transaction.CraftingTransaction; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.item.Item; /** * @author CreeperFace */ public class CraftingTransferMaterialAction extends InventoryAction { private int slot; public CraftingTransferMaterialAction(Item sourceItem, Item targetItem, int slot) { super(sourceItem, targetItem); this.slot = slot; } @Override public void onAddToTransaction(InventoryTransaction transaction) { if (transaction instanceof CraftingTransaction) { if (this.sourceItem.isNull()) { ((CraftingTransaction) transaction).setInput(this.slot, this.targetItem); } else if (this.targetItem.isNull()) { ((CraftingTransaction) transaction).setExtraOutput(this.slot, this.sourceItem); } else { throw new RuntimeException("Invalid " + getClass().getName() + ", either source or target item must be air, got source: " + this.sourceItem + ", target: " + this.targetItem); } } else { throw new RuntimeException(getClass().getName() + " can only be added to CraftingTransactions"); } } @Override public boolean isValid(Player source) { return true; } @Override public boolean execute(Player source) { return true; } @Override public void onExecuteSuccess(Player $source) { } @Override public void onExecuteFail(Player source) { } }
1,618
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
InventoryAction.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/inventory/transaction/action/InventoryAction.java
package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.item.Item; /** * @author CreeperFace */ public abstract class InventoryAction { private long creationTime; protected Item sourceItem; protected Item targetItem; public InventoryAction(Item sourceItem, Item targetItem) { this.sourceItem = sourceItem; this.targetItem = targetItem; this.creationTime = System.currentTimeMillis(); } public long getCreationTime() { return creationTime; } /** * Returns the item that was present before the action took place. * * @return Item */ public Item getSourceItem() { return sourceItem.clone(); } /** * Returns the item that the action attempted to replace the source item with. */ public Item getTargetItem() { return targetItem.clone(); } /** * Called by inventory transactions before any actions are processed. If this returns false, the transaction will * be cancelled. */ public boolean onPreExecute(Player source) { return true; } /** * Returns whether this action is currently valid. This should perform any necessary sanity checks. */ abstract public boolean isValid(Player source); /** * Called when the action is added to the specified InventoryTransaction. */ public void onAddToTransaction(InventoryTransaction transaction) { } /** * Performs actions needed to complete the inventory-action server-side. Returns if it was successful. Will return * false if plugins cancelled events. This will only be called if the transaction which it is part of is considered * valid. */ abstract public boolean execute(Player source); /** * Performs additional actions when this inventory-action completed successfully. */ abstract public void onExecuteSuccess(Player $source); /** * Performs additional actions when this inventory-action did not complete successfully. */ abstract public void onExecuteFail(Player source); }
2,201
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ChunkManager.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/ChunkManager.java
package cn.nukkit.level; import cn.nukkit.level.format.generic.BaseFullChunk; /** * author: MagicDroidX * Nukkit Project */ public interface ChunkManager { int getBlockIdAt(int x, int y, int z); void setBlockIdAt(int x, int y, int z, int id); int getBlockDataAt(int x, int y, int z); void setBlockDataAt(int x, int y, int z, int data); BaseFullChunk getChunk(int chunkX, int chunkZ); void setChunk(int chunkX, int chunkZ); void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk); long getSeed(); }
546
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Location.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/Location.java
package cn.nukkit.level; import cn.nukkit.math.Vector3; import cn.nukkit.utils.LevelException; /** * author: MagicDroidX * Nukkit Project */ public class Location extends Position { public double yaw; public double pitch; public Location() { this(0); } public Location(double x) { this(x, 0); } public Location(double x, double y) { this(x, y, 0); } public Location(double x, double y, double z, Level level) { this(x, y, z, 0, 0, level); } public Location(double x, double y, double z) { this(x, y, z, 0); } public Location(double x, double y, double z, double yaw) { this(x, y, z, yaw, 0); } public Location(double x, double y, double z, double yaw, double pitch) { this(x, y, z, yaw, pitch, null); } public Location(double x, double y, double z, double yaw, double pitch, Level level) { this.x = x; this.y = y; this.z = z; this.yaw = yaw; this.pitch = pitch; this.level = level; } public static Location fromObject(Vector3 pos) { return fromObject(pos, null, 0.0f, 0.0f); } public static Location fromObject(Vector3 pos, Level level) { return fromObject(pos, level, 0.0f, 0.0f); } public static Location fromObject(Vector3 pos, Level level, double yaw) { return fromObject(pos, level, yaw, 0.0f); } public static Location fromObject(Vector3 pos, Level level, double yaw, double pitch) { return new Location(pos.x, pos.y, pos.z, yaw, pitch, (level == null) ? ((pos instanceof Position) ? ((Position) pos).level : null) : level); } public double getYaw() { return this.yaw; } public double getPitch() { return this.pitch; } @Override public String toString() { return "Location (level=" + (this.isValid() ? this.getLevel().getName() : "null") + ", x=" + this.x + ", y=" + this.y + ", z=" + this.z + ", yaw=" + this.yaw + ", pitch=" + this.pitch + ")"; } @Override public Location getLocation() { if (this.isValid()) return new Location(this.x, this.y, this.z, this.yaw, this.pitch, this.level); else throw new LevelException("Undefined Level reference"); } @Override public Location add(double x) { return this.add(x, 0, 0); } @Override public Location add(double x, double y) { return this.add(x, y, 0); } @Override public Location add(double x, double y, double z) { return new Location(this.x + x, this.y + y, this.z + z, this.yaw, this.pitch, this.level); } @Override public Location add(Vector3 x) { return new Location(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ(), this.yaw, this.pitch, this.level); } @Override public Location subtract() { return this.subtract(0, 0, 0); } @Override public Location subtract(double x) { return this.subtract(x, 0, 0); } @Override public Location subtract(double x, double y) { return this.subtract(x, y, 0); } @Override public Location subtract(double x, double y, double z) { return this.add(-x, -y, -z); } @Override public Location subtract(Vector3 x) { return this.add(-x.getX(), -x.getY(), -x.getZ()); } @Override public Location multiply(double number) { return new Location(this.x * number, this.y * number, this.z * number, this.yaw, this.pitch, this.level); } @Override public Location divide(double number) { return new Location(this.x / number, this.y / number, this.z / number, this.yaw, this.pitch, this.level); } @Override public Location ceil() { return new Location((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z), this.yaw, this.pitch, this.level); } @Override public Location floor() { return new Location(this.getFloorX(), this.getFloorY(), this.getFloorZ(), this.yaw, this.pitch, this.level); } @Override public Location round() { return new Location(Math.round(this.x), Math.round(this.y), Math.round(this.z), this.yaw, this.pitch, this.level); } @Override public Location abs() { return new Location((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z), this.yaw, this.pitch, this.level); } public Vector3 getDirectionVector() { double pitch = ((getPitch() + 90) * Math.PI) / 180; double yaw = ((getYaw() + 90) * Math.PI) / 180; double x = Math.sin(pitch) * Math.cos(yaw); double z = Math.sin(pitch) * Math.sin(yaw); double y = Math.cos(pitch); return new Vector3(x, y, z).normalize(); } @Override public Location clone() { return (Location) super.clone(); } }
4,913
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Position.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/Position.java
package cn.nukkit.level; import cn.nukkit.block.Block; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.utils.LevelException; /** * author: MagicDroidX * Nukkit Project */ public class Position extends Vector3 { public Level level; public Position() { this(0, 0, 0, null); } public Position(double x) { this(x, 0, 0, null); } public Position(double x, double y) { this(x, y, 0, null); } public Position(double x, double y, double z) { this(x, y, z, null); } public Position(double x, double y, double z, Level level) { this.x = x; this.y = y; this.z = z; this.level = level; } public static Position fromObject(Vector3 pos) { return fromObject(pos, null); } public static Position fromObject(Vector3 pos, Level level) { return new Position(pos.x, pos.y, pos.z, level); } public Level getLevel() { return this.level; } public Position setLevel(Level level) { this.level = level; return this; } public boolean isValid() { return this.level != null; } public boolean setStrong() { return false; } public boolean setWeak() { return false; } public Position getSide(BlockFace face) { return this.getSide(face, 1); } public Position getSide(BlockFace face, int step) { if (!this.isValid()) { throw new LevelException("Undefined Level reference"); } return Position.fromObject(super.getSide(face, step), this.level); } @Override public String toString() { return "Position(level=" + (this.isValid() ? this.getLevel().getName() : "null") + ",x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; } @Override public Position setComponents(double x, double y, double z) { this.x = x; this.y = y; this.z = z; return this; } public Block getLevelBlock() { if (this.isValid()) return this.level.getBlock(this); else throw new LevelException("Undefined Level reference"); } public Location getLocation() { if (this.isValid()) return new Location(this.x, this.y, this.z, 0, 0, this.level); else throw new LevelException("Undefined Level reference"); } @Override public Position add(double x) { return this.add(x, 0, 0); } @Override public Position add(double x, double y) { return this.add(x, y, 0); } @Override public Position add(double x, double y, double z) { return new Position(this.x + x, this.y + y, this.z + z, this.level); } @Override public Position add(Vector3 x) { return new Position(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ(), this.level); } @Override public Position subtract() { return this.subtract(0, 0, 0); } @Override public Position subtract(double x) { return this.subtract(x, 0, 0); } @Override public Position subtract(double x, double y) { return this.subtract(x, y, 0); } @Override public Position subtract(double x, double y, double z) { return this.add(-x, -y, -z); } @Override public Position subtract(Vector3 x) { return this.add(-x.getX(), -x.getY(), -x.getZ()); } @Override public Position multiply(double number) { return new Position(this.x * number, this.y * number, this.z * number, this.level); } @Override public Position divide(double number) { return new Position(this.x / number, this.y / number, this.z / number, this.level); } @Override public Position ceil() { return new Position((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z), this.level); } @Override public Position floor() { return new Position(this.getFloorX(), this.getFloorY(), this.getFloorZ(), this.level); } @Override public Position round() { return new Position(Math.round(this.x), Math.round(this.y), Math.round(this.z), this.level); } @Override public Position abs() { return new Position((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z), this.level); } @Override public Position clone() { return (Position) super.clone(); } }
4,475
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Explosion.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/Explosion.java
package cn.nukkit.level; import cn.nukkit.block.Block; import cn.nukkit.block.BlockAir; import cn.nukkit.block.BlockTNT; import cn.nukkit.entity.Entity; import cn.nukkit.event.block.BlockUpdateEvent; import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityExplodeEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.particle.HugeExplodeSeedParticle; import cn.nukkit.math.*; import cn.nukkit.network.protocol.ExplodePacket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ThreadLocalRandom; /** * author: Angelic47 * Nukkit Project */ public class Explosion { private final int rays = 16; //Rays private final Level level; private final Position source; private final double size; private List<Block> affectedBlocks = new ArrayList<>(); private final double stepLen = 0.3d; private final Object what; public Explosion(Position center, double size, Entity what) { this.level = center.getLevel(); this.source = center; this.size = Math.max(size, 0); this.what = what; } /** * @return bool * @deprecated */ public boolean explode() { if (explodeA()) { return explodeB(); } return false; } /** * @return bool */ public boolean explodeA() { if (this.size < 0.1) { return false; } Vector3 vector = new Vector3(0, 0, 0); Vector3 vBlock = new Vector3(0, 0, 0); int mRays = this.rays - 1; for (int i = 0; i < this.rays; ++i) { for (int j = 0; j < this.rays; ++j) { for (int k = 0; k < this.rays; ++k) { if (i == 0 || i == mRays || j == 0 || j == mRays || k == 0 || k == mRays) { vector.setComponents((double) i / (double) mRays * 2d - 1, (double) j / (double) mRays * 2d - 1, (double) k / (double) mRays * 2d - 1); double len = vector.length(); vector.setComponents((vector.x / len) * this.stepLen, (vector.y / len) * this.stepLen, (vector.z / len) * this.stepLen); double pointerX = this.source.x; double pointerY = this.source.y; double pointerZ = this.source.z; for (double blastForce = this.size * (ThreadLocalRandom.current().nextInt(700, 1301)) / 1000d; blastForce > 0; blastForce -= this.stepLen * 0.75d) { int x = (int) pointerX; int y = (int) pointerY; int z = (int) pointerZ; vBlock.x = pointerX >= x ? x : x - 1; vBlock.y = pointerY >= y ? y : y - 1; vBlock.z = pointerZ >= z ? z : z - 1; if (vBlock.y < 0 || vBlock.y > 255) { break; } Block block = this.level.getBlock(vBlock); if (block.getId() != 0) { blastForce -= (block.getResistance() / 5 + 0.3d) * this.stepLen; if (blastForce > 0) { if (!this.affectedBlocks.contains(block)) { this.affectedBlocks.add(block); } } } pointerX += vector.x; pointerY += vector.y; pointerZ += vector.z; } } } } } return true; } public boolean explodeB() { HashMap<BlockVector3, Boolean> updateBlocks = new HashMap<>(); List<Vector3> send = new ArrayList<>(); Vector3 source = (new Vector3(this.source.x, this.source.y, this.source.z)).floor(); double yield = (1d / this.size) * 100d; if (this.what instanceof Entity) { EntityExplodeEvent ev = new EntityExplodeEvent((Entity) this.what, this.source, this.affectedBlocks, yield); this.level.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { return false; } else { yield = ev.getYield(); this.affectedBlocks = ev.getBlockList(); } } double explosionSize = this.size * 2d; double minX = NukkitMath.floorDouble(this.source.x - explosionSize - 1); double maxX = NukkitMath.ceilDouble(this.source.x + explosionSize + 1); double minY = NukkitMath.floorDouble(this.source.y - explosionSize - 1); double maxY = NukkitMath.ceilDouble(this.source.y + explosionSize + 1); double minZ = NukkitMath.floorDouble(this.source.z - explosionSize - 1); double maxZ = NukkitMath.ceilDouble(this.source.z + explosionSize + 1); AxisAlignedBB explosionBB = new SimpleAxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); Entity[] list = this.level.getNearbyEntities(explosionBB, this.what instanceof Entity ? (Entity) this.what : null); for (Entity entity : list) { double distance = entity.distance(this.source) / explosionSize; if (distance <= 1) { Vector3 motion = entity.subtract(this.source).normalize(); int exposure = 1; double impact = (1 - distance) * exposure; int damage = (int) (((impact * impact + impact) / 2) * 8 * explosionSize + 1); if (this.what instanceof Entity) { entity.attack(new EntityDamageByEntityEvent((Entity) this.what, entity, DamageCause.ENTITY_EXPLOSION, damage)); } else if (this.what instanceof Block) { entity.attack(new EntityDamageByBlockEvent((Block) this.what, entity, DamageCause.BLOCK_EXPLOSION, damage)); } else { entity.attack(new EntityDamageEvent(entity, DamageCause.BLOCK_EXPLOSION, damage)); } entity.setMotion(motion.multiply(impact)); } } ItemBlock air = new ItemBlock(new BlockAir()); //Iterator iter = this.affectedBlocks.entrySet().iterator(); for (Block block : this.affectedBlocks) { //Block block = (Block) ((HashMap.Entry) iter.next()).getValue(); if (block.getId() == Block.TNT) { ((BlockTNT) block).prime(new NukkitRandom().nextRange(10, 30)); } else if (Math.random() * 100 < yield) { for (Item drop : block.getDrops(air)) { this.level.dropItem(block.add(0.5, 0.5, 0.5), drop); } } this.level.setBlockIdAt((int) block.x, (int) block.y, (int) block.z, 0); Vector3 pos = new Vector3(block.x, block.y, block.z); for (BlockFace side : BlockFace.values()) { Vector3 sideBlock = pos.getSide(side); BlockVector3 index = Level.blockHash((int) sideBlock.x, (int) sideBlock.y, (int) sideBlock.z); if (!this.affectedBlocks.contains(sideBlock) && !updateBlocks.containsKey(index)) { BlockUpdateEvent ev = new BlockUpdateEvent(this.level.getBlock(sideBlock)); this.level.getServer().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { ev.getBlock().onUpdate(Level.BLOCK_UPDATE_NORMAL); } updateBlocks.put(index, true); } } send.add(new Vector3(block.x - source.x, block.y - source.y, block.z - source.z)); } ExplodePacket pk = new ExplodePacket(); pk.x = (float) this.source.x; pk.y = (float) this.source.y; pk.z = (float) this.source.z; pk.radius = (float) this.size; pk.records = send.stream().toArray(Vector3[]::new); this.level.addChunkPacket((int) source.x >> 4, (int) source.z >> 4, pk); this.level.addParticle(new HugeExplodeSeedParticle(this.source)); this.level.addSound(new Vector3(this.source.x, this.source.y, this.source.z), Sound.RANDOM_EXPLODE); return true; } }
8,663
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ChunkLoader.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/ChunkLoader.java
package cn.nukkit.level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.Vector3; /** * author: MagicDroidX * Nukkit Project */ public interface ChunkLoader { Integer getLoaderId(); boolean isLoaderActive(); Position getPosition(); double getX(); double getZ(); Level getLevel(); void onChunkChanged(FullChunk chunk); void onChunkLoaded(FullChunk chunk); void onChunkUnloaded(FullChunk chunk); void onChunkPopulated(FullChunk chunk); void onBlockChanged(Vector3 block); }
547
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
LevelProviderConverter.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/LevelProviderConverter.java
package cn.nukkit.level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.LevelProvider; import cn.nukkit.level.format.anvil.Anvil; import cn.nukkit.level.format.anvil.Chunk; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.format.generic.ChunkConverter; import cn.nukkit.level.format.leveldb.LevelDB; import cn.nukkit.level.format.mcregion.McRegion; import cn.nukkit.level.format.mcregion.RegionLoader; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.LevelException; import cn.nukkit.utils.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteOrder; import java.util.regex.Matcher; import java.util.regex.Pattern; class LevelProviderConverter { private LevelProvider provider; private Class<? extends LevelProvider> toClass; private Level level; private String path; LevelProviderConverter(Level level, String path) { this.level = level; this.path = path; } LevelProviderConverter from(LevelProvider provider) { if (!(provider instanceof McRegion) && !(provider instanceof LevelDB)) { throw new IllegalArgumentException("From type can be only McRegion or LevelDB"); } this.provider = provider; return this; } LevelProviderConverter to(Class<? extends LevelProvider> toClass) { if (toClass != Anvil.class) { throw new IllegalArgumentException("To type can be only Anvil"); } this.toClass = toClass; return this; } LevelProvider perform() throws IOException { new File(path).mkdir(); File dat = new File(provider.getPath(), "level.dat.old"); new File(provider.getPath(), "level.dat").renameTo(dat); Utils.copyFile(dat, new File(path, "level.dat")); LevelProvider result; try { if (provider instanceof LevelDB) { try (FileInputStream stream = new FileInputStream(path + "level.dat")) { stream.skip(8); CompoundTag levelData = NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN); if (levelData != null) { NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", levelData), new FileOutputStream(path + "level.dat")); } else { throw new IOException("LevelData can not be null"); } } catch (IOException e) { throw new LevelException("Invalid level.dat"); } } result = toClass.getConstructor(Level.class, String.class).newInstance(level, path); } catch (Exception e) { throw new RuntimeException(e); } if (toClass == Anvil.class) { if (provider instanceof McRegion) { new File(path, "region").mkdir(); for (File file : new File(provider.getPath() + "region/").listFiles()) { Matcher m = Pattern.compile("-?\\d+").matcher(file.getName()); int regionX, regionZ; try { if (m.find()) { regionX = Integer.parseInt(m.group()); } else continue; if (m.find()) { regionZ = Integer.parseInt(m.group()); } else continue; } catch (NumberFormatException e) { continue; } RegionLoader region = new RegionLoader(provider, regionX, regionZ); for (Integer index : region.getLocationIndexes()) { int chunkX = index & 0x1f; int chunkZ = index >> 5; BaseFullChunk old = region.readChunk(chunkX, chunkZ); if (old == null) continue; int x = (regionX << 5) | chunkX; int z = (regionZ << 5) | chunkZ; FullChunk chunk = new ChunkConverter(result) .from(old) .to(Chunk.class) .perform(); result.saveChunk(x, z, chunk); } region.close(); } } if (provider instanceof LevelDB) { new File(path, "region").mkdir(); for (byte[] key : ((LevelDB) provider).getTerrainKeys()) { int x = getChunkX(key); int z = getChunkZ(key); BaseFullChunk old = ((LevelDB) provider).readChunk(x, z); FullChunk chunk = new ChunkConverter(result) .from(old) .to(Chunk.class) .perform(); result.saveChunk(x, z, chunk); } } result.doGarbageCollection(); } return result; } private static int getChunkX(byte[] key) { return (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0]; } private static int getChunkZ(byte[] key) { return (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4]; } }
5,537
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
GameRule.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/GameRule.java
package cn.nukkit.level; import java.util.Optional; public enum GameRule { COMMAND_BLOCK_OUTPUT("commandBlockOutput"), DO_DAYLIGHT_CYCLE("doDaylightCycle"), DO_ENTITY_DROPS("doEntityDrops"), DO_FIRE_TICK("doFireTick"), DO_MOB_LOOT("doMobLoot"), DO_MOB_SPAWNING("doMobSpawning"), DO_TILE_DROPS("doTileDrops"), DO_WEATHER_CYCLE("doWeatherCycle"), DROWNING_DAMAGE("drowningDamage"), FALL_DAMAGE("fallDamage"), FIRE_DAMAGE("fireDamage"), KEEP_INVENTORY("keepInventory"), MOB_GRIEFING("mobGriefing"), NATURAL_REGENERATION("naturalRegeneration"), PVP("pvp"), SEND_COMMAND_FEEDBACK("sendCommandFeedback"), SHOW_COORDINATES("showCoordinates"), TNT_EXPLODES("tntExplodes"), SHOW_DEATH_MESSAGE("showDeathMessage"); private final String name; GameRule(String name) { this.name = name; } public static Optional<GameRule> parseString(String gameRuleString) { for (GameRule gameRule: values()) { if (gameRule.getName().equalsIgnoreCase(gameRuleString)) { return Optional.of(gameRule); } } return Optional.empty(); } public static String[] getNames() { String[] stringValues = new String[values().length]; for (int i = 0; i < values().length; i++) { stringValues[i] = values()[i].getName(); } return stringValues; } public String getName() { return name; } }
1,488
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Level.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/Level.java
package cn.nukkit.level; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.Block; import cn.nukkit.block.BlockAir; import cn.nukkit.block.BlockRedstoneComparator; import cn.nukkit.block.BlockRedstoneDiode; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityChest; import cn.nukkit.collection.PrimitiveList; import cn.nukkit.entity.Entity; import cn.nukkit.entity.item.EntityItem; import cn.nukkit.entity.item.EntityXPOrb; import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.entity.weather.EntityLightning; import cn.nukkit.event.block.BlockBreakEvent; import cn.nukkit.event.block.BlockPlaceEvent; import cn.nukkit.event.block.BlockUpdateEvent; import cn.nukkit.event.level.*; import cn.nukkit.event.player.PlayerInteractEvent; import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.event.weather.LightningStrikeEvent; import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.format.Chunk; import cn.nukkit.level.format.ChunkSection; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.LevelProvider; import cn.nukkit.level.format.anvil.Anvil; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.format.generic.BaseLevelProvider; import cn.nukkit.level.format.generic.EmptyChunkSection; import cn.nukkit.level.format.leveldb.LevelDB; import cn.nukkit.level.format.mcregion.McRegion; import cn.nukkit.level.generator.Generator; import cn.nukkit.level.generator.task.*; import cn.nukkit.level.particle.DestroyBlockParticle; import cn.nukkit.level.particle.Particle; import cn.nukkit.math.*; import cn.nukkit.math.BlockFace.Plane; import cn.nukkit.metadata.BlockMetadataStore; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.metadata.Metadatable; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.*; import cn.nukkit.network.protocol.*; import cn.nukkit.plugin.Plugin; import cn.nukkit.potion.Effect; import cn.nukkit.scheduler.AsyncTask; import cn.nukkit.scheduler.BlockUpdateScheduler; import cn.nukkit.timings.LevelTimings; import cn.nukkit.utils.*; import co.aikar.timings.Timings; import co.aikar.timings.TimingsHistory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.io.File; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ThreadLocalRandom; /** * author: MagicDroidX Nukkit Project */ public class Level implements ChunkManager, Metadatable { private static int levelIdCounter = 1; private static int chunkLoaderCounter = 1; public static int COMPRESSION_LEVEL = 8; public static final int BLOCK_UPDATE_NORMAL = 1; public static final int BLOCK_UPDATE_RANDOM = 2; public static final int BLOCK_UPDATE_SCHEDULED = 3; public static final int BLOCK_UPDATE_WEAK = 4; public static final int BLOCK_UPDATE_TOUCH = 5; public static final int BLOCK_UPDATE_REDSTONE = 6; public static final int BLOCK_UPDATE_TICK = 7; public static final int TIME_DAY = 0; public static final int TIME_SUNSET = 12000; public static final int TIME_NIGHT = 14000; public static final int TIME_SUNRISE = 23000; public static final int TIME_FULL = 24000; public static final int DIMENSION_OVERWORLD = 0; public static final int DIMENSION_NETHER = 1; // Lower values use less memory public static final int MAX_BLOCK_CACHE = 512; // The blocks that can randomly tick private static final boolean[] randomTickBlocks = new boolean[256]; static { randomTickBlocks[Block.GRASS] = true; randomTickBlocks[Block.FARMLAND] = true; randomTickBlocks[Block.MYCELIUM] = true; randomTickBlocks[Block.SAPLING] = true; randomTickBlocks[Block.LEAVES] = true; randomTickBlocks[Block.LEAVES2] = true; randomTickBlocks[Block.SNOW_LAYER] = true; randomTickBlocks[Block.ICE] = true; randomTickBlocks[Block.LAVA] = true; randomTickBlocks[Block.STILL_LAVA] = true; randomTickBlocks[Block.CACTUS] = true; randomTickBlocks[Block.BEETROOT_BLOCK] = true; randomTickBlocks[Block.CARROT_BLOCK] = true; randomTickBlocks[Block.POTATO_BLOCK] = true; randomTickBlocks[Block.MELON_STEM] = true; randomTickBlocks[Block.PUMPKIN_STEM] = true; randomTickBlocks[Block.WHEAT_BLOCK] = true; randomTickBlocks[Block.SUGARCANE_BLOCK] = true; randomTickBlocks[Block.RED_MUSHROOM] = true; randomTickBlocks[Block.BROWN_MUSHROOM] = true; randomTickBlocks[Block.NETHER_WART_BLOCK] = true; randomTickBlocks[Block.FIRE] = true; randomTickBlocks[Block.GLOWING_REDSTONE_ORE] = true; randomTickBlocks[Block.COCOA_BLOCK] = true; } private final Long2ObjectOpenHashMap<BlockEntity> blockEntities = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Player> players = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Entity> entities = new Long2ObjectOpenHashMap<>(); public final Long2ObjectOpenHashMap<Entity> updateEntities = new Long2ObjectOpenHashMap<>(); public final Long2ObjectOpenHashMap<BlockEntity> updateBlockEntities = new Long2ObjectOpenHashMap<>(); private boolean cacheChunks = false; private final Server server; private final int levelId; private LevelProvider provider; private final Int2ObjectOpenHashMap<ChunkLoader> loaders = new Int2ObjectOpenHashMap<>(); private final Map<Integer, Integer> loaderCounter = new HashMap<>(); private final Long2ObjectOpenHashMap<Map<Integer, ChunkLoader>> chunkLoaders = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Map<Integer, Player>> playerLoaders = new Long2ObjectOpenHashMap<>(); private Long2ObjectOpenHashMap<List<DataPacket>> chunkPackets = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Long> unloadQueue = new Long2ObjectOpenHashMap<>(); private float time; public boolean stopTime; public float skyLightSubtracted; private String folderName; private Vector3 mutableBlock; // Avoid OOM, gc'd references result in whole chunk being sent (possibly higher cpu) private Long2ObjectOpenHashMap<SoftReference<Map<Character, Object>>> changedBlocks = new Long2ObjectOpenHashMap<>(); // Storing the vector is redundant private final Object changeBlocksPresent = new Object(); // Storing extra blocks past 512 is redundant private final Map<Character, Object> changeBlocksFullMap = new HashMap<Character, Object>() { @Override public int size() { return Character.MAX_VALUE; } }; private final BlockUpdateScheduler updateQueue; // private final TreeSet<BlockUpdateEntry> updateQueue = new TreeSet<>(); // private final List<BlockUpdateEntry> nextTickUpdates = Lists.newArrayList(); //private final Map<BlockVector3, Integer> updateQueueIndex = new HashMap<>(); private final Long2ObjectOpenHashMap<Map<Integer, Player>> chunkSendQueue = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Boolean> chunkSendTasks = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Boolean> chunkPopulationQueue = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Boolean> chunkPopulationLock = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap<Boolean> chunkGenerationQueue = new Long2ObjectOpenHashMap<>(); private int chunkGenerationQueueSize = 8; private int chunkPopulationQueueSize = 2; private boolean autoSave = true; private BlockMetadataStore blockMetadata; private boolean useSections; private Position temporalPosition; private Vector3 temporalVector; private final Block[] blockStates; public int sleepTicks = 0; private int chunkTickRadius; private final Long2ObjectOpenHashMap<Integer> chunkTickList = new Long2ObjectOpenHashMap<>(); private int chunksPerTicks; private boolean clearChunksOnTick; protected int updateLCG = (new Random()).nextInt(); public LevelTimings timings; private int tickRate; public int tickRateTime = 0; public int tickRateCounter = 0; private Class<? extends Generator> generator; private Generator generatorInstance; private boolean raining = false; private int rainTime = 0; private boolean thundering = false; private int thunderTime = 0; private long levelCurrentTick = 0; private int dimension; public GameRules gameRules; public Level(Server server, String name, String path, Class<? extends LevelProvider> provider) { this.blockStates = Block.fullList; this.levelId = levelIdCounter++; this.blockMetadata = new BlockMetadataStore(this); this.server = server; this.autoSave = server.getAutoSave(); boolean convert = provider == McRegion.class || provider == LevelDB.class; try { if (convert) { String newPath = new File(path).getParent() + "/" + name + ".old/"; new File(path).renameTo(new File(newPath)); this.provider = provider.getConstructor(Level.class, String.class).newInstance(this, newPath); } else { this.provider = provider.getConstructor(Level.class, String.class).newInstance(this, path); } } catch (Exception e) { throw new LevelException("Caused by " + Utils.getExceptionMessage(e)); } this.timings = new LevelTimings(this); if (convert) { this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.level.updating", TextFormat.GREEN + this.provider.getName() + TextFormat.WHITE)); LevelProvider old = this.provider; try { this.provider = new LevelProviderConverter(this, path) .from(old) .to(Anvil.class) .perform(); } catch (IOException e) { throw new RuntimeException(e); } old.close(); } this.provider.updateLevelName(name); this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.level.preparing", TextFormat.GREEN + this.provider.getName() + TextFormat.WHITE)); this.generator = Generator.getGenerator(this.provider.getGenerator()); try { this.useSections = (boolean) provider.getMethod("usesChunkSection").invoke(null); } catch (Exception e) { throw new RuntimeException(e); } this.folderName = name; this.time = this.provider.getTime(); this.raining = this.provider.isRaining(); this.rainTime = this.provider.getRainTime(); if (this.rainTime <= 0) { setRainTime(ThreadLocalRandom.current().nextInt(168000) + 12000); } this.thundering = this.provider.isThundering(); this.thunderTime = this.provider.getThunderTime(); if (this.thunderTime <= 0) { setThunderTime(ThreadLocalRandom.current().nextInt(168000) + 12000); } this.levelCurrentTick = this.provider.getCurrentTick(); this.updateQueue = new BlockUpdateScheduler(this, levelCurrentTick); this.chunkTickRadius = Math.min(this.server.getViewDistance(), Math.max(1, (Integer) this.server.getConfig("chunk-ticking.tick-radius", 4))); this.chunksPerTicks = (int) this.server.getConfig("chunk-ticking.per-tick", 40); this.chunkGenerationQueueSize = (int) this.server.getConfig("chunk-generation.queue-size", 8); this.chunkPopulationQueueSize = (int) this.server.getConfig("chunk-generation.population-queue-size", 2); this.chunkTickList.clear(); this.clearChunksOnTick = (boolean) this.server.getConfig("chunk-ticking.clear-tick-list", true); this.cacheChunks = (boolean) this.server.getConfig("chunk-sending.cache-chunks", false); this.temporalPosition = new Position(0, 0, 0, this); this.temporalVector = new Vector3(0, 0, 0); this.tickRate = 1; this.skyLightSubtracted = this.calculateSkylightSubtracted(1); } public static long chunkHash(int x, int z) { return (((long) x) << 32) | (z & 0xffffffffL); } public static BlockVector3 blockHash(Vector3 block) { return blockHash(block.x, block.y, block.z); } public static char localBlockHash(double x, double y, double z) { byte hi = (byte) (((int) x & 15) + (((int) z & 15) << 4)); byte lo = (byte) y; return (char) (((hi & 0xFF) << 8) | (lo & 0xFF)); } public static Vector3 getBlockXYZ(long chunkHash, char blockHash) { int hi = (byte) (blockHash >>> 8); int lo = (byte) blockHash; int y = lo & 0xFF; int x = (hi & 0xF) + (getHashX(chunkHash) << 4); int z = ((hi >> 4) & 0xF) + (getHashZ(chunkHash) << 4); return new Vector3(x, y, z); } public static BlockVector3 blockHash(double x, double y, double z) { return new BlockVector3((int) x, (int) y, (int) z); } public static int chunkBlockHash(int x, int y, int z) { return (x << 12) | (z << 8) | y; } public static int getHashX(long hash) { return (int) (hash >> 32); } public static int getHashZ(long hash) { return (int) hash; } public static Vector3 getBlockXYZ(BlockVector3 hash) { return new Vector3(hash.x, hash.y, hash.z); } public static Chunk.Entry getChunkXZ(long hash) { return new Chunk.Entry(getHashX(hash), getHashZ(hash)); } public static int generateChunkLoaderId(ChunkLoader loader) { if (loader.getLoaderId() == null || loader.getLoaderId() == 0) { return chunkLoaderCounter++; } else { throw new IllegalStateException("ChunkLoader has a loader id already assigned: " + loader.getLoaderId()); } } public int getTickRate() { return tickRate; } public int getTickRateTime() { return tickRateTime; } public void setTickRate(int tickRate) { this.tickRate = tickRate; } public void initLevel() { try { this.generatorInstance = this.generator.getConstructor(Map.class) .newInstance(this.provider.getGeneratorOptions()); } catch (Exception e) { throw new RuntimeException(e); } this.generatorInstance.init(this, new NukkitRandom(this.getSeed())); this.dimension = this.generatorInstance.getDimension(); this.gameRules = this.provider.getGamerules(); this.registerGenerator(); } public void registerGenerator() { int size = this.server.getScheduler().getAsyncTaskPoolSize(); for (int i = 0; i < size; ++i) { this.server.getScheduler().scheduleAsyncTask(new GeneratorRegisterTask(this, this.generatorInstance)); } } public void unregisterGenerator() { int size = this.server.getScheduler().getAsyncTaskPoolSize(); for (int i = 0; i < size; ++i) { this.server.getScheduler().scheduleAsyncTask(new GeneratorUnregisterTask(this)); } } public BlockMetadataStore getBlockMetadata() { return this.blockMetadata; } public Server getServer() { return server; } final public LevelProvider getProvider() { return this.provider; } final public int getId() { return this.levelId; } public void close() { if (this.getAutoSave()) { this.save(); } this.unregisterGenerator(); this.provider.close(); this.provider = null; this.blockMetadata = null; this.temporalPosition = null; this.server.getLevels().remove(this.levelId); } public void addSound(Vector3 pos, Sound sound) { this.addSound(pos, sound, 1, 1, (Player[]) null); } public void addSound(Vector3 pos, Sound sound, float volume, float pitch) { this.addSound(pos, sound, volume, pitch, (Player[]) null); } public void addSound(Vector3 pos, Sound sound, float volume, float pitch, Collection<Player> players) { this.addSound(pos, sound, volume, pitch, players.stream().toArray(Player[]::new)); } public void addSound(Vector3 pos, Sound sound, float volume, float pitch, Player... players) { Preconditions.checkArgument(volume >= 0 && volume <= 1, "Sound volume must be between 0 and 1"); Preconditions.checkArgument(pitch >= 0, "Sound pitch must be higher than 0"); PlaySoundPacket packet = new PlaySoundPacket(); packet.name = sound.getSound(); packet.volume = 1; packet.pitch = 1; packet.x = pos.getFloorX(); packet.y = pos.getFloorY(); packet.z = pos.getFloorZ(); if (players == null || players.length == 0) { addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, packet); } else { Server.broadcastPacket(players, packet); } } /** * Broadcasts sound to players * * @param pos position where sound should be played * @param type ID of the sound from cn.nukkit.network.protocol.LevelSoundEventPacket */ public void addLevelSoundEvent(Vector3 pos, int type, int pitch, int data) { this.addLevelSoundEvent(pos, type, pitch, data, false); } public void addLevelSoundEvent(Vector3 pos, int type, int pitch, int data, boolean isGlobal) { LevelSoundEventPacket pk = new LevelSoundEventPacket(); pk.sound = type; pk.pitch = pitch; pk.extraData = data; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.isGlobal = isGlobal; this.addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); } public void addParticle(Particle particle) { this.addParticle(particle, (Player[]) null); } public void addParticle(Particle particle, Player player) { this.addParticle(particle, new Player[]{player}); } public void addParticle(Particle particle, Player[] players) { DataPacket[] packets = particle.encode(); if (players == null) { if (packets != null) { for (DataPacket packet : packets) { this.addChunkPacket((int) particle.x >> 4, (int) particle.z >> 4, packet); } } } else { if (packets != null) { if (packets.length == 1) { Server.broadcastPacket(players, packets[0]); } else { this.server.batchPackets(players, packets, false); } } } } public void addParticle(Particle particle, Collection<Player> players) { this.addParticle(particle, players.stream().toArray(Player[]::new)); } public boolean getAutoSave() { return this.autoSave; } public void setAutoSave(boolean autoSave) { this.autoSave = autoSave; } public boolean unload() { return this.unload(false); } public boolean unload(boolean force) { LevelUnloadEvent ev = new LevelUnloadEvent(this); if (this == this.server.getDefaultLevel() && !force) { ev.setCancelled(); } this.server.getPluginManager().callEvent(ev); if (!force && ev.isCancelled()) { return false; } this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.level.unloading", TextFormat.GREEN + this.getName() + TextFormat.WHITE)); Level defaultLevel = this.server.getDefaultLevel(); for (Player player : new ArrayList<>(this.getPlayers().values())) { if (this == defaultLevel || defaultLevel == null) { player.close(player.getLeaveMessage(), "Forced default level unload"); } else { player.teleport(this.server.getDefaultLevel().getSafeSpawn()); } } if (this == defaultLevel) { this.server.setDefaultLevel(null); } this.close(); return true; } public Map<Integer, Player> getChunkPlayers(int chunkX, int chunkZ) { long index = Level.chunkHash(chunkX, chunkZ); if (this.playerLoaders.containsKey(index)) { return new HashMap<>(this.playerLoaders.get(index)); } else { return new HashMap<>(); } } public ChunkLoader[] getChunkLoaders(int chunkX, int chunkZ) { long index = Level.chunkHash(chunkX, chunkZ); if (this.chunkLoaders.containsKey(index)) { return this.chunkLoaders.get(index).values().stream().toArray(ChunkLoader[]::new); } else { return new ChunkLoader[0]; } } public void addChunkPacket(int chunkX, int chunkZ, DataPacket packet) { long index = Level.chunkHash(chunkX, chunkZ); if (!this.chunkPackets.containsKey(index)) { this.chunkPackets.put(index, new ArrayList<>()); } this.chunkPackets.get(index).add(packet); } public void registerChunkLoader(ChunkLoader loader, int chunkX, int chunkZ) { this.registerChunkLoader(loader, chunkX, chunkZ, true); } public void registerChunkLoader(ChunkLoader loader, int chunkX, int chunkZ, boolean autoLoad) { int hash = loader.getLoaderId(); long index = Level.chunkHash(chunkX, chunkZ); if (!this.chunkLoaders.containsKey(index)) { this.chunkLoaders.put(index, new HashMap<>()); this.playerLoaders.put(index, new HashMap<>()); } else if (this.chunkLoaders.get(index).containsKey(hash)) { return; } this.chunkLoaders.get(index).put(hash, loader); if (loader instanceof Player) { this.playerLoaders.get(index).put(hash, (Player) loader); } if (!this.loaders.containsKey(hash)) { this.loaderCounter.put(hash, 1); this.loaders.put(hash, loader); } else { this.loaderCounter.put(hash, this.loaderCounter.get(hash) + 1); } this.cancelUnloadChunkRequest(hash); if (autoLoad) { this.loadChunk(chunkX, chunkZ); } } public void unregisterChunkLoader(ChunkLoader loader, int chunkX, int chunkZ) { int hash = loader.getLoaderId(); long index = Level.chunkHash(chunkX, chunkZ); Map<Integer, ChunkLoader> chunkLoadersIndex = this.chunkLoaders.get(index); if (chunkLoadersIndex != null) { ChunkLoader oldLoader = chunkLoadersIndex.remove(hash); if (oldLoader != null) { if (chunkLoadersIndex.isEmpty()) { this.chunkLoaders.remove(index); this.playerLoaders.remove(index); this.unloadChunkRequest(chunkX, chunkZ, true); } else { Map<Integer, Player> playerLoadersIndex = this.playerLoaders.get(index); playerLoadersIndex.remove(hash); } int count = this.loaderCounter.get(hash); if (--count == 0) { this.loaderCounter.remove(hash); this.loaders.remove(hash); } else { this.loaderCounter.put(hash, count); } } } } public void checkTime() { if (!this.stopTime) { this.time += tickRate; } } public void sendTime(Player... players) { /*if (this.stopTime) { //TODO SetTimePacket pk0 = new SetTimePacket(); pk0.time = (int) this.time; player.dataPacket(pk0); }*/ SetTimePacket pk = new SetTimePacket(); pk.time = (int) this.time; Server.broadcastPacket(players, pk); } public void sendTime() { sendTime(this.players.values().stream().toArray(Player[]::new)); } public GameRules getGameRules() { return gameRules; } public void doTick(int currentTick) { this.timings.doTick.startTiming(); updateBlockLight(lightQueue); this.checkTime(); // Tick Weather this.rainTime--; if (this.rainTime <= 0) { if (!this.setRaining(!this.raining)) { if (this.raining) { setRainTime(ThreadLocalRandom.current().nextInt(12000) + 12000); } else { setRainTime(ThreadLocalRandom.current().nextInt(168000) + 12000); } } } this.thunderTime--; if (this.thunderTime <= 0) { if (!this.setThundering(!this.thundering)) { if (this.thundering) { setThunderTime(ThreadLocalRandom.current().nextInt(12000) + 3600); } else { setThunderTime(ThreadLocalRandom.current().nextInt(168000) + 12000); } } } if (this.isThundering()) { Map<Long, ? extends FullChunk> chunks = getChunks(); if (chunks instanceof Long2ObjectOpenHashMap) { Long2ObjectOpenHashMap<? extends FullChunk> fastChunks = (Long2ObjectOpenHashMap) chunks; ObjectIterator<? extends Long2ObjectMap.Entry<? extends FullChunk>> iter = fastChunks.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { Long2ObjectMap.Entry<? extends FullChunk> entry = iter.next(); performThunder(entry.getLongKey(), entry.getValue()); } } else { for (Map.Entry<Long, ? extends FullChunk> entry : getChunks().entrySet()) { performThunder(entry.getKey(), entry.getValue()); } } } this.skyLightSubtracted = this.calculateSkylightSubtracted(1); this.levelCurrentTick++; this.unloadChunks(); this.timings.doTickPending.startTiming(); int polled = 0; this.updateQueue.tick(this.getCurrentTick()); this.timings.doTickPending.stopTiming(); TimingsHistory.entityTicks += this.updateEntities.size(); this.timings.entityTick.startTiming(); if (!this.updateEntities.isEmpty()) { for (long id : new ArrayList<>(this.updateEntities.keySet())) { Entity entity = this.updateEntities.get(id); if (entity.closed || !entity.onUpdate(currentTick)) { this.updateEntities.remove(id); } } } this.timings.entityTick.stopTiming(); TimingsHistory.tileEntityTicks += this.updateBlockEntities.size(); this.timings.blockEntityTick.startTiming(); if (!this.updateBlockEntities.isEmpty()) { for (long id : new ArrayList<>(this.updateBlockEntities.keySet())) { if (!this.updateBlockEntities.get(id).onUpdate()) { this.updateBlockEntities.remove(id); } } } this.timings.blockEntityTick.stopTiming(); this.timings.tickChunks.startTiming(); this.tickChunks(); this.timings.tickChunks.stopTiming(); if (!this.changedBlocks.isEmpty()) { if (!this.players.isEmpty()) { ObjectIterator<Long2ObjectMap.Entry<SoftReference<Map<Character, Object>>>> iter = changedBlocks.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { Long2ObjectMap.Entry<SoftReference<Map<Character, Object>>> entry = iter.next(); long index = entry.getKey(); Map<Character, Object> blocks = entry.getValue().get(); int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); if (blocks == null || blocks.size() > MAX_BLOCK_CACHE) { FullChunk chunk = this.getChunk(chunkX, chunkZ); for (Player p : this.getChunkPlayers(chunkX, chunkZ).values()) { p.onChunkChanged(chunk); } } else { Collection<Player> toSend = this.getChunkPlayers(chunkX, chunkZ).values(); Player[] playerArray = toSend.toArray(new Player[toSend.size()]); Vector3[] blocksArray = new Vector3[blocks.size()]; int i = 0; for (char blockHash : blocks.keySet()) { Vector3 hash = getBlockXYZ(index, blockHash); blocksArray[i++] = hash; } this.sendBlocks(playerArray, blocksArray, UpdateBlockPacket.FLAG_ALL); } } } this.changedBlocks.clear(); } this.processChunkRequest(); if (this.sleepTicks > 0 && --this.sleepTicks <= 0) { this.checkSleep(); } for (long index : this.chunkPackets.keySet()) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); Player[] chunkPlayers = this.getChunkPlayers(chunkX, chunkZ).values().stream().toArray(Player[]::new); if (chunkPlayers.length > 0) { for (DataPacket pk : this.chunkPackets.get(index)) { Server.broadcastPacket(chunkPlayers, pk); } } } if(gameRules.isStale()) { GameRulesChangedPacket packet = new GameRulesChangedPacket(); packet.gameRules = gameRules; Server.broadcastPacket(players.values().toArray(new Player[players.size()]), packet); gameRules.refresh(); } this.chunkPackets.clear(); this.timings.doTick.stopTiming(); } private void performThunder(long index, FullChunk chunk) { if (areNeighboringChunksLoaded(index)) return; if (ThreadLocalRandom.current().nextInt(10000) == 0) { this.updateLCG = this.updateLCG * 3 + 1013904223; int LCG = this.updateLCG >> 2; int chunkX = chunk.getX() * 16; int chunkZ = chunk.getZ() * 16; Vector3 vector = this.adjustPosToNearbyEntity(new Vector3(chunkX + (LCG & 15), 0, chunkZ + (LCG >> 8 & 15))); int bId = this.getBlockIdAt(vector.getFloorX(), vector.getFloorY(), vector.getFloorZ()); if (bId != Block.TALL_GRASS && bId != Block.WATER) vector.y += 1; CompoundTag nbt = new CompoundTag() .putList(new ListTag<DoubleTag>("Pos").add(new DoubleTag("", vector.x)) .add(new DoubleTag("", vector.y)).add(new DoubleTag("", vector.z))) .putList(new ListTag<DoubleTag>("Motion").add(new DoubleTag("", 0)) .add(new DoubleTag("", 0)).add(new DoubleTag("", 0))) .putList(new ListTag<FloatTag>("Rotation").add(new FloatTag("", 0)) .add(new FloatTag("", 0))); EntityLightning bolt = new EntityLightning(chunk, nbt); LightningStrikeEvent ev = new LightningStrikeEvent(this, bolt); getServer().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { bolt.spawnToAll(); } else { bolt.setEffect(false); } this.addLevelSoundEvent(vector, LevelSoundEventPacket.SOUND_THUNDER, 93, -1, false); this.addLevelSoundEvent(vector, LevelSoundEventPacket.SOUND_EXPLODE, 93, -1, false); } } public Vector3 adjustPosToNearbyEntity(Vector3 pos) { pos.y = this.getHighestBlockAt(pos.getFloorX(), pos.getFloorZ()); AxisAlignedBB axisalignedbb = new SimpleAxisAlignedBB(pos.x, pos.y, pos.z, pos.getX(), 255, pos.getZ()).expand(3, 3, 3); List<Entity> list = new ArrayList<>(); for (Entity entity : this.getCollidingEntities(axisalignedbb)) { if (entity.isAlive() && canBlockSeeSky(entity)) { list.add(entity); } } if (!list.isEmpty()) { return list.get(ThreadLocalRandom.current().nextInt(list.size())).getPosition(); } else { if (pos.getY() == -1) { pos = pos.up(2); } return pos; } } public void checkSleep() { if (this.players.isEmpty()) { return; } boolean resetTime = true; for (Player p : this.getPlayers().values()) { if (!p.isSleeping()) { resetTime = false; break; } } if (resetTime) { int time = this.getTime() % Level.TIME_FULL; if (time >= Level.TIME_NIGHT && time < Level.TIME_SUNRISE) { this.setTime(this.getTime() + Level.TIME_FULL - time); for (Player p : this.getPlayers().values()) { p.stopSleep(); } } } } public void sendBlockExtraData(int x, int y, int z, int id, int data) { this.sendBlockExtraData(x, y, z, id, data, this.getChunkPlayers(x >> 4, z >> 4).values()); } public void sendBlockExtraData(int x, int y, int z, int id, int data, Player[] players) { LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_SET_DATA; pk.x = x + 0.5f; pk.y = y + 0.5f; pk.z = z + 0.5f; pk.data = (data << 8) | id; Server.broadcastPacket(players, pk); } public void sendBlockExtraData(int x, int y, int z, int id, int data, Collection<Player> players) { LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_SET_DATA; pk.x = x + 0.5f; pk.y = y + 0.5f; pk.z = z + 0.5f; pk.data = (data << 8) | id; Server.broadcastPacket(players, pk); } public void sendBlocks(Player[] target, Vector3[] blocks) { this.sendBlocks(target, blocks, UpdateBlockPacket.FLAG_NONE); } public void sendBlocks(Player[] target, Vector3[] blocks, int flags) { this.sendBlocks(target, blocks, flags, false); } public void sendBlocks(Player[] target, Vector3[] blocks, int flags, boolean optimizeRebuilds) { int size = 0; for (int i = 0; i < blocks.length; i++) { if (blocks[i] != null) size++; } int packetIndex = 0; UpdateBlockPacket[] packets = new UpdateBlockPacket[size]; if (optimizeRebuilds) { Map<Long, Boolean> chunks = new HashMap<>(); for (Vector3 b : blocks) { if (b == null) { continue; } boolean first = false; long index = Level.chunkHash((int) b.x >> 4, (int) b.z >> 4); if (!chunks.containsKey(index)) { chunks.put(index, true); first = true; } UpdateBlockPacket updateBlockPacket = new UpdateBlockPacket(); if (b instanceof Block) { updateBlockPacket.x = (int) ((Block) b).x; updateBlockPacket.y = (int) ((Block) b).y; updateBlockPacket.z = (int) ((Block) b).z; updateBlockPacket.blockId = ((Block) b).getId(); updateBlockPacket.blockData = ((Block) b).getDamage(); updateBlockPacket.flags = first ? flags : UpdateBlockPacket.FLAG_NONE; } else { int fullBlock = this.getFullBlock((int) b.x, (int) b.y, (int) b.z); updateBlockPacket.x = (int) b.x; updateBlockPacket.y = (int) b.y; updateBlockPacket.z = (int) b.z; updateBlockPacket.blockId = fullBlock >> 4; updateBlockPacket.blockData = fullBlock & 0xf; updateBlockPacket.flags = first ? flags : UpdateBlockPacket.FLAG_NONE; } packets[packetIndex++] = updateBlockPacket; } } else { for (Vector3 b : blocks) { if (b == null) { continue; } UpdateBlockPacket updateBlockPacket = new UpdateBlockPacket(); if (b instanceof Block) { updateBlockPacket.x = (int) ((Block) b).x; updateBlockPacket.y = (int) ((Block) b).y; updateBlockPacket.z = (int) ((Block) b).z; updateBlockPacket.blockId = ((Block) b).getId(); updateBlockPacket.blockData = ((Block) b).getDamage(); updateBlockPacket.flags = flags; } else { int fullBlock = this.getFullBlock((int) b.x, (int) b.y, (int) b.z); updateBlockPacket.x = (int) b.x; updateBlockPacket.y = (int) b.y; updateBlockPacket.z = (int) b.z; updateBlockPacket.blockId = fullBlock >> 4; updateBlockPacket.blockData = fullBlock & 0xf; updateBlockPacket.flags = flags; } packets[packetIndex++] = updateBlockPacket; } } this.server.batchPackets(target, packets); } private void tickChunks() { if (this.chunksPerTicks <= 0 || this.loaders.isEmpty()) { this.chunkTickList.clear(); return; } int chunksPerLoader = Math.min(200, Math.max(1, (int) (((double) (this.chunksPerTicks - this.loaders.size()) / this.loaders.size() + 0.5)))); int randRange = 3 + chunksPerLoader / 30; randRange = randRange > this.chunkTickRadius ? this.chunkTickRadius : randRange; ThreadLocalRandom random = ThreadLocalRandom.current(); if (!this.loaders.isEmpty()) { for (ChunkLoader loader : this.loaders.values()) { int chunkX = (int) loader.getX() >> 4; int chunkZ = (int) loader.getZ() >> 4; long index = Level.chunkHash(chunkX, chunkZ); int existingLoaders = Math.max(0, this.chunkTickList.getOrDefault(index, 0)); this.chunkTickList.put(index, (Integer) (existingLoaders + 1)); for (int chunk = 0; chunk < chunksPerLoader; ++chunk) { int dx = random.nextInt(2 * randRange) - randRange; int dz = random.nextInt(2 * randRange) - randRange; long hash = Level.chunkHash(dx + chunkX, dz + chunkZ); if (!this.chunkTickList.containsKey(hash) && provider.isChunkLoaded(hash)) { this.chunkTickList.put(hash, (Integer) (-1)); } } } } int blockTest = 0; if (!chunkTickList.isEmpty()) { ObjectIterator<Long2ObjectMap.Entry<Integer>> iter = chunkTickList.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { Long2ObjectMap.Entry<Integer> entry = iter.next(); long index = entry.getLongKey(); if (!areNeighboringChunksLoaded(index)) { iter.remove(); continue; } int loaders = entry.getValue(); int chunkX = getHashX(index); int chunkZ = getHashZ(index); FullChunk chunk; if ((chunk = this.getChunk(chunkX, chunkZ, false)) == null) { iter.remove(); continue; } else if (loaders <= 0) { iter.remove(); } for (Entity entity : chunk.getEntities().values()) { entity.scheduleUpdate(); } int tickSpeed = 3; if (tickSpeed > 0) { if (this.useSections) { for (ChunkSection section : ((Chunk) chunk).getSections()) { if (!(section instanceof EmptyChunkSection)) { int Y = section.getY(); this.updateLCG = this.updateLCG * 3 + 1013904223; int k = this.updateLCG >> 2; for (int i = 0; i < tickSpeed; ++i, k >>= 10) { int x = k & 0x0f; int y = k >> 8 & 0x0f; int z = k >> 16 & 0x0f; int fullId = section.getFullBlock(x, y, z); int blockId = fullId >> 4; if (randomTickBlocks[blockId]) { Block block = Block.get(fullId, this, chunkX * 16 + x, (Y << 4) + y, chunkZ * 16 + z); block.onUpdate(BLOCK_UPDATE_RANDOM); } } } } } else { for (int Y = 0; Y < 8 && (Y < 3 || blockTest != 0); ++Y) { blockTest = 0; this.updateLCG = this.updateLCG * 3 + 1013904223; int k = this.updateLCG >> 2; for (int i = 0; i < tickSpeed; ++i, k >>= 10) { int x = k & 0x0f; int y = k >> 8 & 0x0f; int z = k >> 16 & 0x0f; int fullId = chunk.getFullBlock(x, y + (Y << 4), z); int blockId = fullId >> 4; blockTest |= fullId; if (this.randomTickBlocks[blockId]) { Block block = Block.get(fullId, this, x, y + (Y << 4), z); block.onUpdate(BLOCK_UPDATE_RANDOM); } } } } } } } if (this.clearChunksOnTick) { this.chunkTickList.clear(); } } public boolean save() { return this.save(false); } public boolean save(boolean force) { if (!this.getAutoSave() && !force) { return false; } this.server.getPluginManager().callEvent(new LevelSaveEvent(this)); this.provider.setTime((int) this.time); this.provider.setRaining(this.raining); this.provider.setRainTime(this.rainTime); this.provider.setThundering(this.thundering); this.provider.setThunderTime(this.thunderTime); this.provider.setCurrentTick(this.levelCurrentTick); this.provider.setGameRules(this.gameRules); this.saveChunks(); if (this.provider instanceof BaseLevelProvider) { this.provider.saveLevelData(); } return true; } public void saveChunks() { provider.saveChunks(); } public void updateAroundRedstone(Vector3 pos, BlockFace face) { for (BlockFace side : BlockFace.values()) { /*if(face != null && side == face) { continue; }*/ this.getBlock(pos.getSide(side)).onUpdate(BLOCK_UPDATE_REDSTONE); } } public void updateComparatorOutputLevel(Vector3 v) { for (BlockFace face : Plane.HORIZONTAL) { Vector3 pos = v.getSide(face); if (this.isChunkLoaded((int) pos.x >> 4, (int) pos.z >> 4)) { Block block1 = this.getBlock(pos); if (BlockRedstoneDiode.isDiode(block1)) { block1.onUpdate(BLOCK_UPDATE_REDSTONE); } else if (block1.isNormalBlock()) { pos = pos.getSide(face); block1 = this.getBlock(pos); if (BlockRedstoneDiode.isDiode(block1)) { block1.onUpdate(BLOCK_UPDATE_REDSTONE); } } } } } public void updateAround(Vector3 pos) { updateAround((int) pos.x, (int) pos.y, (int) pos.z); } public void updateAround(int x, int y, int z) { BlockUpdateEvent ev; this.server.getPluginManager().callEvent( ev = new BlockUpdateEvent(this.getBlock(x, y - 1, z))); if (!ev.isCancelled()) { ev.getBlock().onUpdate(BLOCK_UPDATE_NORMAL); } this.server.getPluginManager().callEvent( ev = new BlockUpdateEvent(this.getBlock(x, y + 1, z))); if (!ev.isCancelled()) { ev.getBlock().onUpdate(BLOCK_UPDATE_NORMAL); } this.server.getPluginManager().callEvent( ev = new BlockUpdateEvent(this.getBlock(x - 1, y, z))); if (!ev.isCancelled()) { ev.getBlock().onUpdate(BLOCK_UPDATE_NORMAL); } this.server.getPluginManager().callEvent( ev = new BlockUpdateEvent(this.getBlock(x + 1, y, z))); if (!ev.isCancelled()) { ev.getBlock().onUpdate(BLOCK_UPDATE_NORMAL); } this.server.getPluginManager().callEvent( ev = new BlockUpdateEvent(this.getBlock(x, y, z - 1))); if (!ev.isCancelled()) { ev.getBlock().onUpdate(BLOCK_UPDATE_NORMAL); } this.server.getPluginManager().callEvent( ev = new BlockUpdateEvent(this.getBlock(x, y, z + 1))); if (!ev.isCancelled()) { ev.getBlock().onUpdate(BLOCK_UPDATE_NORMAL); } } public void scheduleUpdate(Block pos, int delay) { this.scheduleUpdate(pos, pos, delay, 0, true); } public void scheduleUpdate(Block block, Vector3 pos, int delay) { this.scheduleUpdate(block, pos, delay, 0, true); } public void scheduleUpdate(Block block, Vector3 pos, int delay, int priority) { this.scheduleUpdate(block, pos, delay, priority, true); } public void scheduleUpdate(Block block, Vector3 pos, int delay, int priority, boolean checkArea) { if (block.getId() == 0 || (checkArea && !this.isChunkLoaded(block.getFloorX() >> 4, block.getFloorZ() >> 4))) { return; } if (block instanceof BlockRedstoneComparator) { MainLogger.getLogger().notice("schedule update: " + getCurrentTick()); } BlockUpdateEntry entry = new BlockUpdateEntry(pos.floor(), block, ((long) delay) + getCurrentTick(), priority); if (!this.updateQueue.contains(entry)) { this.updateQueue.add(entry); } } public boolean cancelSheduledUpdate(Vector3 pos, Block block) { return this.updateQueue.remove(new BlockUpdateEntry(pos, block)); } public boolean isUpdateScheduled(Vector3 pos, Block block) { return this.updateQueue.contains(new BlockUpdateEntry(pos, block)); } public boolean isBlockTickPending(Vector3 pos, Block block) { return this.updateQueue.isBlockTickPending(pos, block); } public Set<BlockUpdateEntry> getPendingBlockUpdates(FullChunk chunk) { int minX = (chunk.getX() << 4) - 2; int maxX = minX + 16 + 2; int minZ = (chunk.getZ() << 4) - 2; int maxZ = minZ + 16 + 2; return this.getPendingBlockUpdates(new SimpleAxisAlignedBB(minX, 0, minZ, maxX, 256, maxZ)); } public Set<BlockUpdateEntry> getPendingBlockUpdates(AxisAlignedBB boundingBox) { return updateQueue.getPendingBlockUpdates(boundingBox); } public Block[] getCollisionBlocks(AxisAlignedBB bb) { return this.getCollisionBlocks(bb, false); } public Block[] getCollisionBlocks(AxisAlignedBB bb, boolean targetFirst) { int minX = NukkitMath.floorDouble(bb.getMinX()); int minY = NukkitMath.floorDouble(bb.getMinY()); int minZ = NukkitMath.floorDouble(bb.getMinZ()); int maxX = NukkitMath.ceilDouble(bb.getMaxX()); int maxY = NukkitMath.ceilDouble(bb.getMaxY()); int maxZ = NukkitMath.ceilDouble(bb.getMaxZ()); List<Block> collides = new ArrayList<>(); if (targetFirst) { for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.getBlock(this.temporalVector.setComponents(x, y, z)); if (block.getId() != 0 && block.collidesWithBB(bb)) { return new Block[]{block}; } } } } } else { for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.getBlock(this.temporalVector.setComponents(x, y, z)); if (block.getId() != 0 && block.collidesWithBB(bb)) { collides.add(block); } } } } } return collides.stream().toArray(Block[]::new); } public boolean isFullBlock(Vector3 pos) { AxisAlignedBB bb; if (pos instanceof Block) { if (((Block) pos).isSolid()) { return true; } bb = ((Block) pos).getBoundingBox(); } else { bb = this.getBlock(pos).getBoundingBox(); } return bb != null && bb.getAverageEdgeLength() >= 1; } public AxisAlignedBB[] getCollisionCubes(Entity entity, AxisAlignedBB bb) { return this.getCollisionCubes(entity, bb, true); } public AxisAlignedBB[] getCollisionCubes(Entity entity, AxisAlignedBB bb, boolean entities) { int minX = NukkitMath.floorDouble(bb.getMinX()); int minY = NukkitMath.floorDouble(bb.getMinY()); int minZ = NukkitMath.floorDouble(bb.getMinZ()); int maxX = NukkitMath.ceilDouble(bb.getMaxX()); int maxY = NukkitMath.ceilDouble(bb.getMaxY()); int maxZ = NukkitMath.ceilDouble(bb.getMaxZ()); List<AxisAlignedBB> collides = new ArrayList<>(); for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.getBlock(this.temporalVector.setComponents(x, y, z)); if (!block.canPassThrough() && block.collidesWithBB(bb)) { collides.add(block.getBoundingBox()); } } } } if (entities) { for (Entity ent : this.getCollidingEntities(bb.grow(0.25f, 0.25f, 0.25f), entity)) { collides.add(ent.boundingBox.clone()); } } return collides.stream().toArray(AxisAlignedBB[]::new); } public boolean hasCollision(Entity entity, AxisAlignedBB bb, boolean entities) { int minX = NukkitMath.floorDouble(bb.getMinX()); int minY = NukkitMath.floorDouble(bb.getMinY()); int minZ = NukkitMath.floorDouble(bb.getMinZ()); int maxX = NukkitMath.ceilDouble(bb.getMaxX()); int maxY = NukkitMath.ceilDouble(bb.getMaxY()); int maxZ = NukkitMath.ceilDouble(bb.getMaxZ()); for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.getBlock(this.temporalVector.setComponents(x, y, z)); if (!block.canPassThrough() && block.collidesWithBB(bb)) { return true; } } } } if (entities) { return this.getCollidingEntities(bb.grow(0.25f, 0.25f, 0.25f), entity).length > 0; } return false; } public int getFullLight(Vector3 pos) { FullChunk chunk = this.getChunk((int) pos.x >> 4, (int) pos.z >> 4, false); int level = 0; if (chunk != null) { level = chunk.getBlockSkyLight((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f); level -= this.skyLightSubtracted; if (level < 15) { level = Math.max(chunk.getBlockLight((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f), level); } } return level; } public int calculateSkylightSubtracted(float tickDiff) { float angle = this.calculateCelestialAngle(getTime(), tickDiff); float light = 1 - (MathHelper.cos(angle * ((float) Math.PI * 2F)) * 2 + 0.5f); light = light < 0 ? 0 : light > 1 ? 1 : light; light = 1 - light; light = (float) ((double) light * ((isRaining() ? 1 : 0) - (double) 5f / 16d)); light = (float) ((double) light * ((isThundering() ? 1 : 0) - (double) 5f / 16d)); light = 1 - light; return (int) (light * 11f); } public float calculateCelestialAngle(int time, float tickDiff) { float angle = ((float) time + tickDiff) / 24000f - 0.25f; if (angle < 0) { ++angle; } if (angle > 1) { --angle; } float i = 1 - (float) ((Math.cos((double) angle * Math.PI) + 1) / 2d); angle = angle + (i - angle) / 3; return angle; } public int getMoonPhase(long worldTime) { return (int) (worldTime / 24000 % 8 + 8) % 8; } public int getFullBlock(int x, int y, int z) { return this.getChunk(x >> 4, z >> 4, false).getFullBlock(x & 0x0f, y & 0xff, z & 0x0f); } public Block getBlock(Vector3 pos) { return this.getBlock(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()); } public Block getBlock(int x, int y, int z) { int fullState; if (y >= 0 && y < 256) { int cx = x >> 4; int cz = z >> 4; BaseFullChunk chunk = getChunk(cx, cz); if (chunk != null) { fullState = chunk.getFullBlock(x & 0xF, y, z & 0xF); } else { fullState = 0; } } else { fullState = 0; } Block block = this.blockStates[fullState & 0xFFF].clone(); block.x = x; block.y = y; block.z = z; block.level = this; return block; } public void updateAllLight(Vector3 pos) { this.updateBlockSkyLight((int) pos.x, (int) pos.y, (int) pos.z); this.addLightUpdate((int) pos.x, (int) pos.y, (int) pos.z); } public void updateBlockSkyLight(int x, int y, int z) { // todo } public void updateBlockLight(Map<Long, Map<Character, Object>> map) { int size = map.size(); if (size == 0) { return; } Queue<BlockVector3> lightPropagationQueue = new ConcurrentLinkedQueue<>(); Queue<Object[]> lightRemovalQueue = new ConcurrentLinkedQueue<>(); Map<BlockVector3, Object> visited = new ConcurrentHashMap<>(8, 0.9f, 1); Map<BlockVector3, Object> removalVisited = new ConcurrentHashMap<>(8, 0.9f, 1); Iterator<Map.Entry<Long, Map<Character, Object>>> iter = map.entrySet().iterator(); while (iter.hasNext() && size-- > 0) { Map.Entry<Long, Map<Character, Object>> entry = iter.next(); iter.remove(); long index = entry.getKey(); Map<Character, Object> blocks = entry.getValue(); int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); int bx = chunkX << 4; int bz = chunkZ << 4; for (char blockHash : blocks.keySet()) { int hi = (byte) (blockHash >>> 8); int lo = (byte) blockHash; int y = lo & 0xFF; int x = (hi & 0xF) + bx; int z = ((hi >> 4) & 0xF) + bz; BaseFullChunk chunk = getChunk(x >> 4, z >> 4, false); if (chunk != null) { int lcx = x & 0xF; int lcz = z & 0xF; int oldLevel = chunk.getBlockLight(lcx, y, lcz); int newLevel = Block.light[chunk.getBlockId(lcx, y, lcz)]; if (oldLevel != newLevel) { this.setBlockLightAt(x, y, z, newLevel); if (newLevel < oldLevel) { removalVisited.put(Level.blockHash(x, y, z), changeBlocksPresent); lightRemovalQueue.add(new Object[]{new BlockVector3(x, y, z), oldLevel}); } else { visited.put(Level.blockHash(x, y, z), changeBlocksPresent); lightPropagationQueue.add(new BlockVector3(x, y, z)); } } } } } while (!lightRemovalQueue.isEmpty()) { Object[] val = lightRemovalQueue.poll(); BlockVector3 node = (BlockVector3) val[0]; int lightLevel = (int) val[1]; this.computeRemoveBlockLight((int) node.x - 1, (int) node.y, (int) node.z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); this.computeRemoveBlockLight((int) node.x + 1, (int) node.y, (int) node.z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); this.computeRemoveBlockLight((int) node.x, (int) node.y - 1, (int) node.z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); this.computeRemoveBlockLight((int) node.x, (int) node.y + 1, (int) node.z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); this.computeRemoveBlockLight((int) node.x, (int) node.y, (int) node.z - 1, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); this.computeRemoveBlockLight((int) node.x, (int) node.y, (int) node.z + 1, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); } while (!lightPropagationQueue.isEmpty()) { BlockVector3 node = lightPropagationQueue.poll(); int lightLevel = this.getBlockLightAt((int) node.x, (int) node.y, (int) node.z) - Block.lightFilter[this.getBlockIdAt((int) node.x, (int) node.y, (int) node.z)]; if (lightLevel >= 1) { this.computeSpreadBlockLight((int) node.x - 1, (int) node.y, (int) node.z, lightLevel, lightPropagationQueue, visited); this.computeSpreadBlockLight((int) node.x + 1, (int) node.y, (int) node.z, lightLevel, lightPropagationQueue, visited); this.computeSpreadBlockLight((int) node.x, (int) node.y - 1, (int) node.z, lightLevel, lightPropagationQueue, visited); this.computeSpreadBlockLight((int) node.x, (int) node.y + 1, (int) node.z, lightLevel, lightPropagationQueue, visited); this.computeSpreadBlockLight((int) node.x, (int) node.y, (int) node.z - 1, lightLevel, lightPropagationQueue, visited); this.computeSpreadBlockLight(node.x, (int) node.y, (int) node.z + 1, lightLevel, lightPropagationQueue, visited); } } } private void computeRemoveBlockLight(int x, int y, int z, int currentLight, Queue<Object[]> queue, Queue<BlockVector3> spreadQueue, Map<BlockVector3, Object> visited, Map<BlockVector3, Object> spreadVisited) { int current = this.getBlockLightAt(x, y, z); BlockVector3 index = Level.blockHash(x, y, z); if (current != 0 && current < currentLight) { this.setBlockLightAt(x, y, z, 0); if (current > 1) { if (!visited.containsKey(index)) { visited.put(index, changeBlocksPresent); queue.add(new Object[]{new BlockVector3(x, y, z), current}); } } } else if (current >= currentLight) { if (!spreadVisited.containsKey(index)) { spreadVisited.put(index, changeBlocksPresent); spreadQueue.add(new BlockVector3(x, y, z)); } } } private void computeSpreadBlockLight(int x, int y, int z, int currentLight, Queue<BlockVector3> queue, Map<BlockVector3, Object> visited) { int current = this.getBlockLightAt(x, y, z); BlockVector3 index = Level.blockHash(x, y, z); if (current < currentLight - 1) { this.setBlockLightAt(x, y, z, currentLight); if (!visited.containsKey(index)) { visited.put(index, changeBlocksPresent); if (currentLight > 1) { queue.add(new BlockVector3(x, y, z)); } } } } private Map<Long, Map<Character, Object>> lightQueue = new ConcurrentHashMap<>(8, 0.9f, 1); public void addLightUpdate(int x, int y, int z) { long index = chunkHash((int) x >> 4, (int) z >> 4); Map<Character, Object> currentMap = lightQueue.get(index); if (currentMap == null) { currentMap = new ConcurrentHashMap<>(8, 0.9f, 1); this.lightQueue.put(index, currentMap); } currentMap.put(Level.localBlockHash(x, y, z), changeBlocksPresent); } public boolean setBlock(Vector3 pos, Block block) { return this.setBlock(pos, block, false); } public boolean setBlock(Vector3 pos, Block block, boolean direct) { return this.setBlock(pos, block, direct, true); } public boolean setBlock(Vector3 pos, Block block, boolean direct, boolean update) { return setBlock((int) pos.x, (int) pos.y, (int) pos.z, block, direct, update); } public boolean setBlock(int x, int y, int z, Block block, boolean direct, boolean update) { if (y < 0 || y >= 256) { return false; } BaseFullChunk chunk = this.getChunk(x >> 4, z >> 4, true); Block blockPrevious; // synchronized (chunk) { blockPrevious = chunk.getAndSetBlock(x & 0xF, y, z & 0xF, block); if (blockPrevious.getFullId() == block.getFullId()) { return false; } // } block.x = x; block.y = y; block.z = z; block.level = this; int cx = x >> 4; int cz = z >> 4; long index = Level.chunkHash(cx, cz); if (direct) { this.sendBlocks(this.getChunkPlayers(cx, cz).values().stream().toArray(Player[]::new), new Block[]{block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); } else { addBlockChange(index, x, y, z); } for (ChunkLoader loader : this.getChunkLoaders(cx, cz)) { loader.onBlockChanged(block); } if (update) { if (blockPrevious.isTransparent() != block.isTransparent() || blockPrevious.getLightLevel() != block.getLightLevel()) { addLightUpdate(x, y, z); } BlockUpdateEvent ev = new BlockUpdateEvent(block); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { for (Entity entity : this.getNearbyEntities(new SimpleAxisAlignedBB(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1))) { entity.scheduleUpdate(); } block = ev.getBlock(); block.onUpdate(BLOCK_UPDATE_NORMAL); this.updateAround(x, y, z); } } return true; } private void addBlockChange(int x, int y, int z) { long index = Level.chunkHash(x >> 4, z >> 4); addBlockChange(index, x, y, z); } private void addBlockChange(long index, int x, int y, int z) { SoftReference<Map<Character, Object>> current = changedBlocks.computeIfAbsent(index, k -> new SoftReference(new HashMap<>())); Map<Character, Object> currentMap = current.get(); if (currentMap != changeBlocksFullMap && currentMap != null) { if (currentMap.size() > MAX_BLOCK_CACHE) { this.changedBlocks.put(index, new SoftReference(changeBlocksFullMap)); } else { currentMap.put(Level.localBlockHash(x, y, z), changeBlocksPresent); } } } public void dropItem(Vector3 source, Item item) { this.dropItem(source, item, null); } public void dropItem(Vector3 source, Item item, Vector3 motion) { this.dropItem(source, item, motion, 10); } public void dropItem(Vector3 source, Item item, Vector3 motion, int delay) { this.dropItem(source, item, motion, false, delay); } public void dropItem(Vector3 source, Item item, Vector3 motion, boolean dropAround, int delay) { if (motion == null) { if (dropAround) { float f = ThreadLocalRandom.current().nextFloat() * 0.5f; float f1 = ThreadLocalRandom.current().nextFloat() * ((float) Math.PI * 2); motion = new Vector3(-MathHelper.sin(f1) * f, 0.20000000298023224, MathHelper.cos(f1) * f); } else { motion = new Vector3(new java.util.Random().nextDouble() * 0.2 - 0.1, 0.2, new java.util.Random().nextDouble() * 0.2 - 0.1); } } CompoundTag itemTag = NBTIO.putItemHelper(item); itemTag.setName("Item"); if (item.getId() > 0 && item.getCount() > 0) { EntityItem itemEntity = new EntityItem( this.getChunk((int) source.getX() >> 4, (int) source.getZ() >> 4, true), new CompoundTag().putList(new ListTag<DoubleTag>("Pos").add(new DoubleTag("", source.getX())) .add(new DoubleTag("", source.getY())).add(new DoubleTag("", source.getZ()))) .putList(new ListTag<DoubleTag>("Motion").add(new DoubleTag("", motion.x)) .add(new DoubleTag("", motion.y)).add(new DoubleTag("", motion.z))) .putList(new ListTag<FloatTag>("Rotation") .add(new FloatTag("", new java.util.Random().nextFloat() * 360)) .add(new FloatTag("", 0))) .putShort("Health", 5).putCompound("Item", itemTag).putShort("PickupDelay", delay)); itemEntity.spawnToAll(); } } public Item useBreakOn(Vector3 vector) { return this.useBreakOn(vector, null); } public Item useBreakOn(Vector3 vector, Item item) { return this.useBreakOn(vector, item, null); } public Item useBreakOn(Vector3 vector, Item item, Player player) { return this.useBreakOn(vector, item, player, false); } public Item useBreakOn(Vector3 vector, Item item, Player player, boolean createParticles) { if (player != null && player.getGamemode() > 1) { return null; } Block target = this.getBlock(vector); Item[] drops; if (item == null) { item = new ItemBlock(new BlockAir(), 0, 0); } if (player != null) { double breakTime = target.getBreakTime(item, player); // this in // block // class if (player.isCreative() && breakTime > 0.15) { breakTime = 0.15; } if (player.hasEffect(Effect.SWIFTNESS)) { breakTime *= 1 - (0.2 * (player.getEffect(Effect.SWIFTNESS).getAmplifier() + 1)); } if (player.hasEffect(Effect.MINING_FATIGUE)) { breakTime *= 1 - (0.3 * (player.getEffect(Effect.MINING_FATIGUE).getAmplifier() + 1)); } Enchantment eff = item.getEnchantment(Enchantment.ID_EFFICIENCY); if (eff != null && eff.getLevel() > 0) { breakTime *= 1 - (0.3 * eff.getLevel()); } breakTime -= 0.15; BlockBreakEvent ev = new BlockBreakEvent(player, target, item, player.isCreative(), (player.lastBreak + breakTime * 1000) > System.currentTimeMillis()); double distance; if (player.isSurvival() && !target.isBreakable(item)) { ev.setCancelled(); } else if (!player.isOp() && (distance = this.server.getSpawnRadius()) > -1) { Vector2 t = new Vector2(target.x, target.z); Vector2 s = new Vector2(this.getSpawnLocation().x, this.getSpawnLocation().z); if (!this.server.getOps().getAll().isEmpty() && t.distance(s) <= distance) { ev.setCancelled(); } } this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { return null; } if (!ev.getInstaBreak() && ev.isFastBreak()) { return null; } player.lastBreak = System.currentTimeMillis(); drops = ev.getDrops(); } else if (!target.isBreakable(item)) { return null; } else { drops = target.getDrops(item); } Block above = this.getBlock(new Vector3(target.x, target.y + 1, target.z)); if (above != null) { if (above.getId() == Item.FIRE) { this.setBlock(above, new BlockAir(), true); } } Tag tag = item.getNamedTagEntry("CanDestroy"); if (tag instanceof ListTag) { boolean canBreak = false; for (Tag v : ((ListTag<Tag>) tag).getAll()) { if (v instanceof StringTag) { Item entry = Item.fromString(((StringTag) v).data); if (entry.getId() > 0 && entry.getBlock() != null && entry.getBlock().getId() == target.getId()) { canBreak = true; break; } } } if (!canBreak) { return null; } } if (createParticles) { Map<Integer, Player> players = this.getChunkPlayers((int) target.x >> 4, (int) target.z >> 4); this.addParticle(new DestroyBlockParticle(target.add(0.5), target), players.values()); if (player != null) { players.remove(player.getLoaderId()); } } target.onBreak(item); BlockEntity blockEntity = this.getBlockEntity(target); if (blockEntity != null) { if (blockEntity instanceof InventoryHolder) { if (blockEntity instanceof BlockEntityChest) { ((BlockEntityChest) blockEntity).unpair(); } for (Item chestItem : ((InventoryHolder) blockEntity).getInventory().getContents().values()) { this.dropItem(target, chestItem); } } blockEntity.close(); this.updateComparatorOutputLevel(target); } item.useOn(target); if (item.isTool() && item.getDamage() >= item.getMaxDurability()) { item = new ItemBlock(new BlockAir(), 0, 0); } if (this.gameRules.getBoolean(GameRule.DO_TILE_DROPS)) { int dropExp = target.getDropExp(); if (player != null) { player.addExperience(dropExp); if (player.isSurvival()) { for (int ii = 1; ii <= dropExp; ii++) { this.dropExpOrb(target, 1); } } } if (player == null || player.isSurvival()) { for (Item drop : drops) { if (drop.getCount() > 0) { this.dropItem(vector.add(0.5, 0.5, 0.5), drop); } } } } return item; } public void dropExpOrb(Vector3 source, int exp) { dropExpOrb(source, exp, null); } public void dropExpOrb(Vector3 source, int exp, Vector3 motion) { dropExpOrb(source, exp, motion, 10); } public void dropExpOrb(Vector3 source, int exp, Vector3 motion, int delay) { motion = (motion == null) ? new Vector3(new java.util.Random().nextDouble() * 0.2 - 0.1, 0.2, new java.util.Random().nextDouble() * 0.2 - 0.1) : motion; CompoundTag nbt = new CompoundTag() .putList(new ListTag<DoubleTag>("Pos").add(new DoubleTag("", source.getX())) .add(new DoubleTag("", source.getY())).add(new DoubleTag("", source.getZ()))) .putList(new ListTag<DoubleTag>("Motion").add(new DoubleTag("", motion.getX())) .add(new DoubleTag("", motion.getY())).add(new DoubleTag("", motion.getZ()))) .putList(new ListTag<FloatTag>("Rotation").add(new FloatTag("", 0)).add(new FloatTag("", 0))); Entity entity = new EntityXPOrb(this.getChunk(source.getFloorX() >> 4, source.getFloorZ() >> 4), nbt); EntityXPOrb xpOrb = (EntityXPOrb) entity; xpOrb.setExp(exp); xpOrb.setPickupDelay(delay); xpOrb.saveNBT(); xpOrb.spawnToAll(); } public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float fy, float fz) { return this.useItemOn(vector, item, face, fx, fy, fz, null); } public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float fy, float fz, Player player) { return this.useItemOn(vector, item, face, fx, fy, fz, player, false); } public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float fy, float fz, Player player, boolean playSound) { Block target = this.getBlock(vector); Block block = target.getSide(face); if (block.y > 255 || block.y < 0) { return null; } if (target.getId() == Item.AIR) { return null; } if (player != null) { PlayerInteractEvent ev = new PlayerInteractEvent(player, item, target, face, target.getId() == 0 ? Action.RIGHT_CLICK_AIR : Action.RIGHT_CLICK_BLOCK); if (player.getGamemode() > 2) { ev.setCancelled(); } int distance = this.server.getSpawnRadius(); if (!player.isOp() && distance > -1) { Vector2 t = new Vector2(target.x, target.z); Vector2 s = new Vector2(this.getSpawnLocation().x, this.getSpawnLocation().z); if (!this.server.getOps().getAll().isEmpty() && t.distance(s) <= distance) { ev.setCancelled(); } } this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { target.onUpdate(BLOCK_UPDATE_TOUCH); if ((!player.isSneaking() || player.getInventory().getItemInHand().isNull()) && target.canBeActivated() && target.onActivate(item, player)) { return item; } if (item.canBeActivated() && item.onActivate(this, player, block, target, face, fx, fy, fz)) { if (item.getCount() <= 0) { item = new ItemBlock(new BlockAir(), 0, 0); return item; } } } else { return null; } } else if (target.canBeActivated() && target.onActivate(item, null)) { return item; } Block hand; if (item.canBePlaced()) { hand = item.getBlock(); hand.position(block); } else { return null; } if (!(block.canBeReplaced() || (hand.getId() == Item.SLAB && block.getId() == Item.SLAB))) { return null; } if (target.canBeReplaced()) { block = target; hand.position(block); } if (!hand.canPassThrough() && hand.getBoundingBox() != null) { Entity[] entities = this.getCollidingEntities(hand.getBoundingBox()); int realCount = 0; for (Entity e : entities) { if (e instanceof EntityArrow || e instanceof EntityItem || (e instanceof Player && ((Player) e).isSpectator())) { continue; } ++realCount; } if (player != null) { Vector3 diff = player.getNextPosition().subtract(player.getPosition()); if (diff.lengthSquared() > 0.00001) { AxisAlignedBB bb = player.getBoundingBox().getOffsetBoundingBox(diff.x, diff.y, diff.z); if (hand.getBoundingBox().intersectsWith(bb)) { ++realCount; } } } if (realCount > 0) { return null; // Entity in block } } Tag tag = item.getNamedTagEntry("CanPlaceOn"); if (tag instanceof ListTag) { boolean canPlace = false; for (Tag v : ((ListTag<Tag>) tag).getAll()) { if (v instanceof StringTag) { Item entry = Item.fromString(((StringTag) v).data); if (entry.getId() > 0 && entry.getBlock() != null && entry.getBlock().getId() == target.getId()) { canPlace = true; break; } } } if (!canPlace) { return null; } } if (player != null) { BlockPlaceEvent event = new BlockPlaceEvent(player, hand, block, target, item); int distance = this.server.getSpawnRadius(); if (!player.isOp() && distance > -1) { Vector2 t = new Vector2(target.x, target.z); Vector2 s = new Vector2(this.getSpawnLocation().x, this.getSpawnLocation().z); if (!this.server.getOps().getAll().isEmpty() && t.distance(s) <= distance) { event.setCancelled(); } } this.server.getPluginManager().callEvent(event); if (event.isCancelled()) { return null; } } if (!hand.place(item, block, target, face, fx, fy, fz, player)) { return null; } if (player != null) { if (!player.isCreative()) { item.setCount(item.getCount() - 1); } } if (playSound) { this.addLevelSoundEvent(hand, LevelSoundEventPacket.SOUND_PLACE, 1, item.getId(), false); } if (item.getCount() <= 0) { item = new ItemBlock(new BlockAir(), 0, 0); } return item; } public Entity getEntity(long entityId) { return this.entities.containsKey(entityId) ? this.entities.get(entityId) : null; } public Entity[] getEntities() { return entities.values().stream().toArray(Entity[]::new); } public Entity[] getCollidingEntities(AxisAlignedBB bb) { return this.getCollidingEntities(bb, null); } public Entity[] getCollidingEntities(AxisAlignedBB bb, Entity entity) { List<Entity> nearby = new ArrayList<>(); if (entity == null || entity.canCollide()) { int minX = NukkitMath.floorDouble((bb.getMinX() - 2) / 16); int maxX = NukkitMath.ceilDouble((bb.getMaxX() + 2) / 16); int minZ = NukkitMath.floorDouble((bb.getMinZ() - 2) / 16); int maxZ = NukkitMath.ceilDouble((bb.getMaxZ() + 2) / 16); for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { for (Entity ent : this.getChunkEntities(x, z).values()) { if ((entity == null || (ent != entity && entity.canCollideWith(ent))) && ent.boundingBox.intersectsWith(bb)) { nearby.add(ent); } } } } } return nearby.stream().toArray(Entity[]::new); } public Entity[] getNearbyEntities(AxisAlignedBB bb) { return this.getNearbyEntities(bb, null); } private static Entity[] EMPTY_ENTITY_ARR = new Entity[0]; private static Entity[] ENTITY_BUFFER = new Entity[512]; public Entity[] getNearbyEntities(AxisAlignedBB bb, Entity entity) { int index = 0; int minX = NukkitMath.floorDouble((bb.getMinX() - 2) * 0.0625); int maxX = NukkitMath.ceilDouble((bb.getMaxX() + 2) * 0.0625); int minZ = NukkitMath.floorDouble((bb.getMinZ() - 2) * 0.0625); int maxZ = NukkitMath.ceilDouble((bb.getMaxZ() + 2) * 0.0625); ArrayList<Entity> overflow = null; for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { for (Entity ent : this.getChunkEntities(x, z).values()) { if (ent != entity && ent.boundingBox.intersectsWith(bb)) { if (index < ENTITY_BUFFER.length) { ENTITY_BUFFER[index] = ent; } else { if (overflow == null) overflow = new ArrayList<>(1024); overflow.add(ent); } index++; } } } } if (index == 0) return EMPTY_ENTITY_ARR; Entity[] copy; if (overflow == null) { copy = Arrays.copyOfRange(ENTITY_BUFFER, 0, index); Arrays.fill(ENTITY_BUFFER, 0, index, null); } else { copy = new Entity[ENTITY_BUFFER.length + overflow.size()]; System.arraycopy(ENTITY_BUFFER, 0, copy, 0, ENTITY_BUFFER.length); for (int i = 0; i < overflow.size(); i++) { copy[ENTITY_BUFFER.length + i] = overflow.get(i); } } return copy; } public Map<Long, BlockEntity> getBlockEntities() { return blockEntities; } public BlockEntity getBlockEntityById(long blockEntityId) { return this.blockEntities.containsKey(blockEntityId) ? this.blockEntities.get(blockEntityId) : null; } public Map<Long, Player> getPlayers() { return players; } public Map<Integer, ChunkLoader> getLoaders() { return loaders; } public BlockEntity getBlockEntity(Vector3 pos) { FullChunk chunk = this.getChunk((int) pos.x >> 4, (int) pos.z >> 4, false); if (chunk != null) { return chunk.getTile((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f); } return null; } public Map<Long, Entity> getChunkEntities(int X, int Z) { FullChunk chunk; return (chunk = this.getChunk(X, Z)) != null ? chunk.getEntities() : Collections.emptyMap(); } public Map<Long, BlockEntity> getChunkBlockEntities(int X, int Z) { FullChunk chunk; return (chunk = this.getChunk(X, Z)) != null ? chunk.getBlockEntities() : Collections.emptyMap(); } @Override public int getBlockIdAt(int x, int y, int z) { return this.getChunk(x >> 4, z >> 4, true).getBlockId(x & 0x0f, y & 0xff, z & 0x0f); } @Override public void setBlockIdAt(int x, int y, int z, int id) { this.getChunk(x >> 4, z >> 4, true).setBlockId(x & 0x0f, y & 0xff, z & 0x0f, id & 0xff); addBlockChange(x, y, z); temporalVector.setComponents(x, y, z); for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { loader.onBlockChanged(temporalVector); } } public int getBlockExtraDataAt(int x, int y, int z) { return this.getChunk(x >> 4, z >> 4, true).getBlockExtraData(x & 0x0f, y & 0xff, z & 0x0f); } public void setBlockExtraDataAt(int x, int y, int z, int id, int data) { this.getChunk(x >> 4, z >> 4, true).setBlockExtraData(x & 0x0f, y & 0xff, z & 0x0f, (data << 8) | id); this.sendBlockExtraData(x, y, z, id, data); } @Override public int getBlockDataAt(int x, int y, int z) { return this.getChunk(x >> 4, z >> 4, true).getBlockData(x & 0x0f, y & 0xff, z & 0x0f); } @Override public void setBlockDataAt(int x, int y, int z, int data) { this.getChunk(x >> 4, z >> 4, true).setBlockData(x & 0x0f, y & 0xff, z & 0x0f, data & 0x0f); addBlockChange(x, y, z); temporalVector.setComponents(x, y, z); for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { loader.onBlockChanged(temporalVector); } } public int getBlockSkyLightAt(int x, int y, int z) { return this.getChunk(x >> 4, z >> 4, true).getBlockSkyLight(x & 0x0f, y & 0xff, z & 0x0f); } public void setBlockSkyLightAt(int x, int y, int z, int level) { this.getChunk(x >> 4, z >> 4, true).setBlockSkyLight(x & 0x0f, y & 0xff, z & 0x0f, level & 0x0f); } public int getBlockLightAt(int x, int y, int z) { return this.getChunk(x >> 4, z >> 4, true).getBlockLight(x & 0x0f, y & 0xff, z & 0x0f); } public void setBlockLightAt(int x, int y, int z, int level) { this.getChunk(x >> 4, z >> 4, true).setBlockLight(x & 0x0f, y & 0xff, z & 0x0f, level & 0x0f); } public int getBiomeId(int x, int z) { return this.getChunk(x >> 4, z >> 4, true).getBiomeId(x & 0x0f, z & 0x0f); } public void setBiomeId(int x, int z, int biomeId) { this.getChunk(x >> 4, z >> 4, true).setBiomeId(x & 0x0f, z & 0x0f, biomeId & 0x0f); } public int getHeightMap(int x, int z) { return this.getChunk(x >> 4, z >> 4, true).getHeightMap(x & 0x0f, z & 0x0f); } public void setHeightMap(int x, int z, int value) { this.getChunk(x >> 4, z >> 4, true).setHeightMap(x & 0x0f, z & 0x0f, value & 0x0f); } public int[] getBiomeColor(int x, int z) { return this.getChunk(x >> 4, z >> 4, true).getBiomeColor(x & 0x0f, z & 0x0f); } public void setBiomeColor(int x, int z, int R, int G, int B) { this.getChunk(x >> 4, z >> 4, true).setBiomeColor(x & 0x0f, z & 0x0f, R, G, B); } public Map<Long,? extends FullChunk> getChunks() { return provider.getLoadedChunks(); } @Override public BaseFullChunk getChunk(int chunkX, int chunkZ) { return this.getChunk(chunkX, chunkZ, false); } public BaseFullChunk getChunk(int chunkX, int chunkZ, boolean create) { long index = Level.chunkHash(chunkX, chunkZ); BaseFullChunk chunk = this.provider.getLoadedChunk(index); if (chunk == null) { chunk = this.forceLoadChunk(index, chunkX, chunkZ, create); } return chunk; } public void generateChunkCallback(int x, int z, BaseFullChunk chunk) { Timings.generationCallbackTimer.startTiming(); long index = Level.chunkHash(x, z); if (this.chunkPopulationQueue.containsKey(index)) { FullChunk oldChunk = this.getChunk(x, z, false); for (int xx = -1; xx <= 1; ++xx) { for (int zz = -1; zz <= 1; ++zz) { this.chunkPopulationLock.remove(Level.chunkHash(x + xx, z + zz)); } } this.chunkPopulationQueue.remove(index); chunk.setProvider(this.provider); this.setChunk(x, z, chunk, false); chunk = this.getChunk(x, z, false); if (chunk != null && (oldChunk == null || !oldChunk.isPopulated()) && chunk.isPopulated() && chunk.getProvider() != null) { this.server.getPluginManager().callEvent(new ChunkPopulateEvent(chunk)); for (ChunkLoader loader : this.getChunkLoaders(x, z)) { loader.onChunkPopulated(chunk); } } } else if (this.chunkGenerationQueue.containsKey(index) || this.chunkPopulationLock.containsKey(index)) { this.chunkGenerationQueue.remove(index); this.chunkPopulationLock.remove(index); chunk.setProvider(this.provider); this.setChunk(x, z, chunk, false); } else { chunk.setProvider(this.provider); this.setChunk(x, z, chunk, false); } Timings.generationCallbackTimer.stopTiming(); } @Override public void setChunk(int chunkX, int chunkZ) { this.setChunk(chunkX, chunkZ, null); } @Override public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk) { this.setChunk(chunkX, chunkZ, chunk, true); } public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk, boolean unload) { if (chunk == null) { return; } long index = Level.chunkHash(chunkX, chunkZ); FullChunk oldChunk = this.getChunk(chunkX, chunkZ, false); if (unload && oldChunk != null) { this.unloadChunk(chunkX, chunkZ, false, false); this.provider.setChunk(chunkX, chunkZ, chunk); } else { Map<Long, Entity> oldEntities = oldChunk != null ? oldChunk.getEntities() : Collections.emptyMap(); Map<Long, BlockEntity> oldBlockEntities = oldChunk != null ? oldChunk.getBlockEntities() : Collections.emptyMap(); if (!oldEntities.isEmpty()) { Iterator<Map.Entry<Long, Entity>> iter = oldEntities.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, Entity> entry = iter.next(); Entity entity = entry.getValue(); chunk.addEntity(entity); if (oldChunk != null) { iter.remove(); oldChunk.removeEntity(entity); entity.chunk = chunk; } } } if (!oldBlockEntities.isEmpty()) { Iterator<Map.Entry<Long, BlockEntity>> iter = oldBlockEntities.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, BlockEntity> entry = iter.next(); BlockEntity blockEntity = entry.getValue(); chunk.addBlockEntity(blockEntity); if (oldChunk != null) { iter.remove(); oldChunk.removeBlockEntity(blockEntity); blockEntity.chunk = chunk; } } } this.provider.setChunk(chunkX, chunkZ, chunk); } chunk.setChanged(); if (!this.isChunkInUse(index)) { this.unloadChunkRequest(chunkX, chunkZ); } else { for (ChunkLoader loader : this.getChunkLoaders(chunkX, chunkZ)) { loader.onChunkChanged(chunk); } } } public int getHighestBlockAt(int x, int z) { return this.getChunk(x >> 4, z >> 4, true).getHighestBlockAt(x & 0x0f, z & 0x0f); } public BlockColor getMapColorAt(int x, int z) { int y = getHighestBlockAt(x, z); while (y > 1) { Block block = getBlock(new Vector3(x, y, z)); BlockColor blockColor = block.getColor(); if (blockColor.getAlpha() == 0x00) { y--; } else { return blockColor; } } return BlockColor.VOID_BLOCK_COLOR; } public boolean isChunkLoaded(int x, int z) { return this.provider.isChunkLoaded(x, z); } private boolean areNeighboringChunksLoaded(long hash) { return this.provider.isChunkLoaded(hash + 1) && this.provider.isChunkLoaded(hash - 1) && this.provider.isChunkLoaded(hash + (1L << 32)) && this.provider.isChunkLoaded(hash - (1L << 32)); } public boolean isChunkGenerated(int x, int z) { FullChunk chunk = this.getChunk(x, z); return chunk != null && chunk.isGenerated(); } public boolean isChunkPopulated(int x, int z) { FullChunk chunk = this.getChunk(x, z); return chunk != null && chunk.isPopulated(); } public Position getSpawnLocation() { return Position.fromObject(this.provider.getSpawn(), this); } public void setSpawnLocation(Vector3 pos) { Position previousSpawn = this.getSpawnLocation(); this.provider.setSpawn(pos); this.server.getPluginManager().callEvent(new SpawnChangeEvent(this, previousSpawn)); SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; pk.x = pos.getFloorX(); pk.y = pos.getFloorY(); pk.z = pos.getFloorZ(); for (Player p : getPlayers().values()) p.dataPacket(pk); } public void requestChunk(int x, int z, Player player) { long index = Level.chunkHash(x, z); if (!this.chunkSendQueue.containsKey(index)) { this.chunkSendQueue.put(index, new HashMap<>()); } this.chunkSendQueue.get(index).put(player.getLoaderId(), player); } private void sendChunk(int x, int z, long index, DataPacket packet) { if (this.chunkSendTasks.containsKey(index)) { for (Player player : this.chunkSendQueue.get(index).values()) { if (player.isConnected() && player.usedChunks.containsKey(index)) { player.sendChunk(x, z, packet); } } this.chunkSendQueue.remove(index); this.chunkSendTasks.remove(index); } } private void processChunkRequest() { this.timings.syncChunkSendTimer.startTiming(); for (Long index : ImmutableList.copyOf(this.chunkSendQueue.keySet())) { if (this.chunkSendTasks.containsKey(index)) { continue; } int x = getHashX(index); int z = getHashZ(index); this.chunkSendTasks.put(index, Boolean.TRUE); BaseFullChunk chunk = getChunk(x, z); if (chunk != null) { BatchPacket packet = chunk.getChunkPacket(); if (packet != null) { this.sendChunk(x, z, index, packet); continue; } } this.timings.syncChunkSendPrepareTimer.startTiming(); AsyncTask task = this.provider.requestChunkTask(x, z); if (task != null) { this.server.getScheduler().scheduleAsyncTask(task); } this.timings.syncChunkSendPrepareTimer.stopTiming(); } this.timings.syncChunkSendTimer.stopTiming(); } public void chunkRequestCallback(long timestamp, int x, int z, byte[] payload) { this.timings.syncChunkSendTimer.startTiming(); long index = Level.chunkHash(x, z); if (this.cacheChunks) { BatchPacket data = Player.getChunkCacheFromData(x, z, payload); BaseFullChunk chunk = getChunk(x, z, false); if (chunk != null && chunk.getChanges() <= timestamp) { chunk.setChunkPacket(data); } this.sendChunk(x, z, index, data); this.timings.syncChunkSendTimer.stopTiming(); return; } if (this.chunkSendTasks.containsKey(index)) { for (Player player : this.chunkSendQueue.get(index).values()) { if (player.isConnected() && player.usedChunks.containsKey(index)) { player.sendChunk(x, z, payload); } } this.chunkSendQueue.remove(index); this.chunkSendTasks.remove(index); } this.timings.syncChunkSendTimer.stopTiming(); } public void removeEntity(Entity entity) { if (entity.getLevel() != this) { throw new LevelException("Invalid Entity level"); } if (entity instanceof Player) { this.players.remove(entity.getId()); this.checkSleep(); } else { entity.close(); } this.entities.remove(entity.getId()); this.updateEntities.remove(entity.getId()); } public void addEntity(Entity entity) { if (entity.getLevel() != this) { throw new LevelException("Invalid Entity level"); } if (entity instanceof Player) { this.players.put(entity.getId(), (Player) entity); } this.entities.put(entity.getId(), entity); } public void addBlockEntity(BlockEntity blockEntity) { if (blockEntity.getLevel() != this) { throw new LevelException("Invalid Block Entity level"); } blockEntities.put(blockEntity.getId(), blockEntity); } public void removeBlockEntity(BlockEntity blockEntity) { if (blockEntity.getLevel() != this) { throw new LevelException("Invalid Block Entity level"); } blockEntities.remove(blockEntity.getId()); updateBlockEntities.remove(blockEntity.getId()); } public boolean isChunkInUse(int x, int z) { return isChunkInUse(Level.chunkHash(x, z)); } public boolean isChunkInUse(long hash) { return this.chunkLoaders.containsKey(hash) && !this.chunkLoaders.get(hash).isEmpty(); } public boolean loadChunk(int x, int z) { return this.loadChunk(x, z, true); } public boolean loadChunk(int x, int z, boolean generate) { long index = Level.chunkHash(x, z); if (this.provider.isChunkLoaded(index)) { return true; } return forceLoadChunk(index, x, z, generate) != null; } private BaseFullChunk forceLoadChunk(long index, int x, int z, boolean generate) { this.timings.syncChunkLoadTimer.startTiming(); BaseFullChunk chunk = this.provider.getChunk(x, z, generate); if (chunk == null) { if (generate) { throw new IllegalStateException("Could not create new Chunk"); } this.timings.syncChunkLoadTimer.stopTiming(); return chunk; } if (chunk.getProvider() != null) { this.server.getPluginManager().callEvent(new ChunkLoadEvent(chunk, !chunk.isGenerated())); } else { this.unloadChunk(x, z, false); this.timings.syncChunkLoadTimer.stopTiming(); return chunk; } chunk.initChunk(); if (!chunk.isLightPopulated() && chunk.isPopulated() && (boolean) this.getServer().getConfig("chunk-ticking.light-updates", false)) { this.getServer().getScheduler().scheduleAsyncTask(new LightPopulationTask(this, chunk)); } if (this.isChunkInUse(index)) { this.unloadQueue.remove(index); for (ChunkLoader loader : this.getChunkLoaders(x, z)) { loader.onChunkLoaded(chunk); } } else { this.unloadQueue.put(index, (Long) System.currentTimeMillis()); } this.timings.syncChunkLoadTimer.stopTiming(); return chunk; } private void queueUnloadChunk(int x, int z) { long index = Level.chunkHash(x, z); this.unloadQueue.put(index, (Long) System.currentTimeMillis()); } public boolean unloadChunkRequest(int x, int z) { return this.unloadChunkRequest(x, z, true); } public boolean unloadChunkRequest(int x, int z, boolean safe) { if ((safe && this.isChunkInUse(x, z)) || this.isSpawnChunk(x, z)) { return false; } this.queueUnloadChunk(x, z); return true; } public void cancelUnloadChunkRequest(int x, int z) { this.cancelUnloadChunkRequest(Level.chunkHash(x, z)); } public void cancelUnloadChunkRequest(long hash) { this.unloadQueue.remove(hash); } public boolean unloadChunk(int x, int z) { return this.unloadChunk(x, z, true); } public boolean unloadChunk(int x, int z, boolean safe) { return this.unloadChunk(x, z, safe, true); } public boolean unloadChunk(int x, int z, boolean safe, boolean trySave) { if (safe && this.isChunkInUse(x, z)) { return false; } if (!this.isChunkLoaded(x, z)) { return true; } this.timings.doChunkUnload.startTiming(); long index = Level.chunkHash(x, z); BaseFullChunk chunk = this.getChunk(x, z); if (chunk != null && chunk.getProvider() != null) { ChunkUnloadEvent ev = new ChunkUnloadEvent(chunk); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { this.timings.doChunkUnload.stopTiming(); return false; } } try { if (chunk != null) { if (trySave && this.getAutoSave()) { int entities = 0; for (Entity e : chunk.getEntities().values()) { if (e instanceof Player) { continue; } ++entities; } if (chunk.hasChanged() || !chunk.getBlockEntities().isEmpty() || entities > 0) { this.provider.setChunk(x, z, chunk); this.provider.saveChunk(x, z); } } for (ChunkLoader loader : this.getChunkLoaders(x, z)) { loader.onChunkUnloaded(chunk); } } this.provider.unloadChunk(x, z, safe); } catch (Exception e) { MainLogger logger = this.server.getLogger(); logger.error(this.server.getLanguage().translateString("nukkit.level.chunkUnloadError", e.toString())); logger.logException(e); } this.timings.doChunkUnload.stopTiming(); return true; } public boolean isSpawnChunk(int X, int Z) { Vector3 spawn = this.provider.getSpawn(); return Math.abs(X - (spawn.getFloorX() >> 4)) <= 1 && Math.abs(Z - (spawn.getFloorZ() >> 4)) <= 1; } public Position getSafeSpawn() { return this.getSafeSpawn(null); } public Position getSafeSpawn(Vector3 spawn) { if (spawn == null || spawn.y < 1) { spawn = this.getSpawnLocation(); } if (spawn != null) { Vector3 v = spawn.floor(); FullChunk chunk = this.getChunk((int) v.x >> 4, (int) v.z >> 4, false); int x = (int) v.x & 0x0f; int z = (int) v.z & 0x0f; if (chunk != null) { int y = (int) Math.min(254, v.y); boolean wasAir = chunk.getBlockId(x, y - 1, z) == 0; for (; y > 0; --y) { int b = chunk.getFullBlock(x, y, z); Block block = Block.get(b >> 4, b & 0x0f); if (this.isFullBlock(block)) { if (wasAir) { y++; break; } } else { wasAir = true; } } for (; y >= 0 && y < 256; ++y) { int b = chunk.getFullBlock(x, y + 1, z); Block block = Block.get(b >> 4, b & 0x0f); if (!this.isFullBlock(block)) { b = chunk.getFullBlock(x, y, z); block = Block.get(b >> 4, b & 0x0f); if (!this.isFullBlock(block)) { return new Position(spawn.x, y == (int) spawn.y ? spawn.y : y, spawn.z, this); } } else { ++y; } } v.y = y; } return new Position(spawn.x, v.y, spawn.z, this); } return null; } public int getTime() { return (int) time; } public boolean isDaytime() { return this.skyLightSubtracted < 4; } public long getCurrentTick() { return this.levelCurrentTick; } public String getName() { return this.provider.getName(); } public String getFolderName() { return this.folderName; } public void setTime(int time) { this.time = time; this.sendTime(); } public void stopTime() { this.stopTime = true; this.sendTime(); } public void startTime() { this.stopTime = false; this.sendTime(); } @Override public long getSeed() { return this.provider.getSeed(); } public void setSeed(int seed) { this.provider.setSeed(seed); } public boolean populateChunk(int x, int z) { return this.populateChunk(x, z, false); } public boolean populateChunk(int x, int z, boolean force) { long index = Level.chunkHash(x, z); if (this.chunkPopulationQueue.containsKey(index) || this.chunkPopulationQueue.size() >= this.chunkPopulationQueueSize && !force) { return false; } BaseFullChunk chunk = this.getChunk(x, z, true); boolean populate; if (!chunk.isPopulated()) { Timings.populationTimer.startTiming(); populate = true; for (int xx = -1; xx <= 1; ++xx) { for (int zz = -1; zz <= 1; ++zz) { if (this.chunkPopulationLock.containsKey(Level.chunkHash(x + xx, z + zz))) { populate = false; break; } } } if (populate) { if (!this.chunkPopulationQueue.containsKey(index)) { this.chunkPopulationQueue.put(index, Boolean.TRUE); for (int xx = -1; xx <= 1; ++xx) { for (int zz = -1; zz <= 1; ++zz) { this.chunkPopulationLock.put(Level.chunkHash(x + xx, z + zz), Boolean.TRUE); } } PopulationTask task = new PopulationTask(this, chunk); this.server.getScheduler().scheduleAsyncTask(task); } } Timings.populationTimer.stopTiming(); return false; } return true; } public void generateChunk(int x, int z) { this.generateChunk(x, z, false); } public void generateChunk(int x, int z, boolean force) { if (this.chunkGenerationQueue.size() >= this.chunkGenerationQueueSize && !force) { return; } long index = Level.chunkHash(x, z); if (!this.chunkGenerationQueue.containsKey(index)) { Timings.generationTimer.startTiming(); this.chunkGenerationQueue.put(index, Boolean.TRUE); GenerationTask task = new GenerationTask(this, this.getChunk(x, z, true)); this.server.getScheduler().scheduleAsyncTask(task); Timings.generationTimer.stopTiming(); } } public void regenerateChunk(int x, int z) { this.unloadChunk(x, z, false); this.cancelUnloadChunkRequest(x, z); this.generateChunk(x, z); } public void doChunkGarbageCollection() { this.timings.doChunkGC.startTiming(); // remove all invaild block entities. List<BlockEntity> toClose = new ArrayList<>(); if (!blockEntities.isEmpty()) { Iterator<Map.Entry<Long, BlockEntity>> iter = blockEntities.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, BlockEntity> entry = iter.next(); BlockEntity aBlockEntity = entry.getValue(); if (aBlockEntity != null) { if (!aBlockEntity.isValid()) { iter.remove(); aBlockEntity.close(); } } else { iter.remove(); } } } for (Map.Entry<Long, ? extends FullChunk> entry : provider.getLoadedChunks().entrySet()) { long index = entry.getKey(); if (!this.unloadQueue.containsKey(index)) { FullChunk chunk = entry.getValue(); int X = chunk.getX(); int Z = chunk.getZ(); if (!this.isSpawnChunk(X, Z)) { this.unloadChunkRequest(X, Z, true); } } } this.provider.doGarbageCollection(); this.timings.doChunkGC.stopTiming(); } public void doGarbageCollection(long allocatedTime) { long start = System.currentTimeMillis(); if (unloadChunks(start, allocatedTime, false)) { allocatedTime = allocatedTime - (System.currentTimeMillis() - start); provider.doGarbageCollection(allocatedTime); } } public void unloadChunks() { this.unloadChunks(false); } public void unloadChunks(boolean force) { unloadChunks(96, force); } public void unloadChunks(int maxUnload, boolean force) { if (!this.unloadQueue.isEmpty()) { long now = System.currentTimeMillis(); PrimitiveList toRemove = null; ObjectIterator<Long2ObjectMap.Entry<Long>> iter = unloadQueue.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { Long2ObjectMap.Entry<Long> entry = iter.next(); long index = entry.getLongKey(); if (isChunkInUse(index)) { continue; } if (!force) { long time = entry.getValue(); if (maxUnload <= 0) { break; } else if (time > (now - 30000)) { continue; } } if (toRemove == null) toRemove = new PrimitiveList(long.class); toRemove.add(index); } if (toRemove != null) { int size = toRemove.size(); for (int i = 0; i < size; i++) { long index = toRemove.getLong(i); int X = getHashX(index); int Z = getHashZ(index); if (this.unloadChunk(X, Z, true)) { this.unloadQueue.remove(index); --maxUnload; } } } } } private int lastUnloadIndex; /** * @param now * @param allocatedTime * @param force * @return true if there is allocated time remaining */ private boolean unloadChunks(long now, long allocatedTime, boolean force) { if (!this.unloadQueue.isEmpty()) { boolean result = true; int maxIterations = this.unloadQueue.size(); if (lastUnloadIndex > maxIterations) lastUnloadIndex = 0; ObjectIterator<Long2ObjectMap.Entry<Long>> iter = this.unloadQueue.long2ObjectEntrySet().fastIterator(); if (lastUnloadIndex != 0) iter.skip(lastUnloadIndex); PrimitiveList toUnload = null; for (int i = 0; i < maxIterations; i++) { if (!iter.hasNext()) { iter = this.unloadQueue.long2ObjectEntrySet().fastIterator(); } Long2ObjectMap.Entry<Long> entry = iter.next(); long index = entry.getLongKey(); if (isChunkInUse(index)) { continue; } if (!force) { long time = entry.getValue(); if (time > (now - 30000)) { continue; } } if (toUnload == null) toUnload = new PrimitiveList(long.class); toUnload.add(index); } if (toUnload != null) { long[] arr = (long[]) toUnload.getArray(); for (long index : arr) { int X = getHashX(index); int Z = getHashZ(index); if (this.unloadChunk(X, Z, true)) { this.unloadQueue.remove(index); if (System.currentTimeMillis() - now >= allocatedTime) { result = false; break; } } } } return result; } else { return true; } } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) throws Exception { this.server.getLevelMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List<MetadataValue> getMetadata(String metadataKey) throws Exception { return this.server.getLevelMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) throws Exception { return this.server.getLevelMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) throws Exception { this.server.getLevelMetadata().removeMetadata(this, metadataKey, owningPlugin); } public void addEntityMotion(int chunkX, int chunkZ, long entityId, double x, double y, double z) { SetEntityMotionPacket pk = new SetEntityMotionPacket(); pk.eid = entityId; pk.motionX = (float) x; pk.motionY = (float) y; pk.motionZ = (float) z; this.addChunkPacket(chunkX, chunkZ, pk); } public void addEntityMovement(int chunkX, int chunkZ, long entityId, double x, double y, double z, double yaw, double pitch, double headYaw) { MoveEntityPacket pk = new MoveEntityPacket(); pk.eid = entityId; pk.x = (float) x; pk.y = (float) y; pk.z = (float) z; pk.yaw = (float) yaw; pk.headYaw = (float) yaw; pk.pitch = (float) pitch; this.addChunkPacket(chunkX, chunkZ, pk); } public boolean isRaining() { return this.raining; } public boolean setRaining(boolean raining) { WeatherChangeEvent ev = new WeatherChangeEvent(this, raining); this.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { return false; } this.raining = raining; LevelEventPacket pk = new LevelEventPacket(); // These numbers are from Minecraft if (raining) { pk.evid = LevelEventPacket.EVENT_START_RAIN; pk.data = ThreadLocalRandom.current().nextInt(50000) + 10000; setRainTime(ThreadLocalRandom.current().nextInt(12000) + 12000); } else { pk.evid = LevelEventPacket.EVENT_STOP_RAIN; setRainTime(ThreadLocalRandom.current().nextInt(168000) + 12000); } Server.broadcastPacket(this.getPlayers().values(), pk); return true; } public int getRainTime() { return this.rainTime; } public void setRainTime(int rainTime) { this.rainTime = rainTime; } public boolean isThundering() { return isRaining() && this.thundering; } public boolean setThundering(boolean thundering) { ThunderChangeEvent ev = new ThunderChangeEvent(this, thundering); this.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { return false; } if (thundering && !isRaining()) { setRaining(true); } this.thundering = thundering; LevelEventPacket pk = new LevelEventPacket(); // These numbers are from Minecraft if (thundering) { pk.evid = LevelEventPacket.EVENT_START_THUNDER; pk.data = ThreadLocalRandom.current().nextInt(50000) + 10000; setThunderTime(ThreadLocalRandom.current().nextInt(12000) + 3600); } else { pk.evid = LevelEventPacket.EVENT_STOP_THUNDER; setThunderTime(ThreadLocalRandom.current().nextInt(168000) + 12000); } Server.broadcastPacket(this.getPlayers().values(), pk); return true; } public int getThunderTime() { return this.thunderTime; } public void setThunderTime(int thunderTime) { this.thunderTime = thunderTime; } public void sendWeather(Player[] players) { if (players == null) { players = this.getPlayers().values().stream().toArray(Player[]::new); } LevelEventPacket pk = new LevelEventPacket(); if (this.isRaining()) { pk.evid = LevelEventPacket.EVENT_START_RAIN; pk.data = ThreadLocalRandom.current().nextInt(50000) + 10000; } else { pk.evid = LevelEventPacket.EVENT_STOP_RAIN; } Server.broadcastPacket(players, pk); if (this.isThundering()) { pk.evid = LevelEventPacket.EVENT_START_THUNDER; pk.data = ThreadLocalRandom.current().nextInt(50000) + 10000; } else { pk.evid = LevelEventPacket.EVENT_STOP_THUNDER; } Server.broadcastPacket(players, pk); } public void sendWeather(Player player) { if (player != null) { this.sendWeather(new Player[]{player}); } } public void sendWeather(Collection<Player> players) { if (players == null) { players = this.getPlayers().values(); } this.sendWeather(players.stream().toArray(Player[]::new)); } public int getDimension() { return dimension; } public boolean canBlockSeeSky(Vector3 pos) { return this.getHighestBlockAt(pos.getFloorX(), pos.getFloorZ()) < pos.getY(); } public int getStrongPower(Vector3 pos, BlockFace direction) { return this.getBlock(pos).getStrongPower(direction); } public int getStrongPower(Vector3 pos) { int i = 0; i = Math.max(i, this.getStrongPower(pos.down(), BlockFace.DOWN)); if (i >= 15) { return i; } else { i = Math.max(i, this.getStrongPower(pos.up(), BlockFace.UP)); if (i >= 15) { return i; } else { i = Math.max(i, this.getStrongPower(pos.north(), BlockFace.NORTH)); if (i >= 15) { return i; } else { i = Math.max(i, this.getStrongPower(pos.south(), BlockFace.SOUTH)); if (i >= 15) { return i; } else { i = Math.max(i, this.getStrongPower(pos.west(), BlockFace.WEST)); if (i >= 15) { return i; } else { i = Math.max(i, this.getStrongPower(pos.east(), BlockFace.EAST)); return i >= 15 ? i : i; } } } } } } public boolean isSidePowered(Vector3 pos, BlockFace face) { return this.getRedstonePower(pos, face) > 0; } public int getRedstonePower(Vector3 pos, BlockFace face) { Block block = this.getBlock(pos); return block.isNormalBlock() ? this.getStrongPower(pos) : block.getWeakPower(face); } public boolean isBlockPowered(Vector3 pos) { return this.getRedstonePower(pos.north(), BlockFace.NORTH) > 0 || this.getRedstonePower(pos.south(), BlockFace.SOUTH) > 0 || this.getRedstonePower(pos.west(), BlockFace.WEST) > 0 || this.getRedstonePower(pos.east(), BlockFace.EAST) > 0 || this.getRedstonePower(pos.down(), BlockFace.DOWN) > 0 || this.getRedstonePower(pos.up(), BlockFace.UP) > 0; } public int isBlockIndirectlyGettingPowered(Vector3 pos) { int power = 0; for (BlockFace face : BlockFace.values()) { int blockPower = this.getRedstonePower(pos.getSide(face), face); if (blockPower >= 15) { return 15; } if (blockPower > power) { power = blockPower; } } return power; } public boolean isAreaLoaded(AxisAlignedBB bb) { if (bb.getMaxY() < 0 || bb.getMinY() >= 256) { return false; } int minX = NukkitMath.floorDouble(bb.getMinX()) >> 4; int minZ = NukkitMath.floorDouble(bb.getMinZ()) >> 4; int maxX = NukkitMath.floorDouble(bb.getMaxX()) >> 4; int maxZ = NukkitMath.floorDouble(bb.getMaxZ()) >> 4; for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { if (!this.isChunkLoaded(x, z)) { return false; } } } return true; } }
123,285
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Sound.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/Sound.java
package cn.nukkit.level; /** * @author CreeperFace */ public enum Sound { AMBIENT_WEATHER_THUNDER("ambient.weather.thunder"), AMBIENT_WEATHER_LIGHTNING_IMPACT("ambient.weather.lightning.impact"), AMBIENT_WEATHER_RAIN("ambient.weather.rain"), BLOCK_FALSE_PERMISSIONS("block.false_permissions"), BLOCK_END_PORTAL_SPAWN("block.end_portal.spawn"), BLOCK_END_PORTAL_FRAME_FILL("block.end_portal_frame.fill"), BLOCK_ITEMFRAME_ADD_ITEM("block.itemframe.add_item"), BLOCK_ITEMFRAME_BREAK("block.itemframe.break"), BLOCK_ITEMFRAME_PLACE("block.itemframe.place"), BLOCK_ITEMFRAME_REMOVE_ITEM("block.itemframe.remove_item"), BLOCK_ITEMFRAME_ROTATE_ITEM("block.itemframe.rotate_item"), BLOCK_CHORUSFLOWER_DEATH("block.chorusflower.death"), BLOCK_CHORUSFLOWER_GROW("block.chorusflower.grow"), BUCKET_EMPTY_LAVA("bucket.empty_lava"), BUCKET_EMPTY_WATER("bucket.empty_water"), BUCKET_FILL_LAVA("bucket.fill_lava"), BUCKET_FILL_WATER("bucket.fill_water"), CAULDRON_EXPLODE("cauldron.explode"), CAULDRON_DYEARMOR("cauldron.dyearmor"), CAULDRON_CLEANARMOR("cauldron.cleanarmor"), CAULDRON_CLEANBANNER("cauldron.cleanbanner"), CAULDRON_FILLPOTION("cauldron.fillpotion"), CAULDRON_TAKEPOTION("cauldron.takepotion"), CAULDRON_FILLWATER("cauldron.fillwater"), CAULDRON_TAKEWATER("cauldron.takewater"), CAULDRON_ADDDYE("cauldron.adddye"), DAMAGE_FALLBIG("damage.fallbig"), DAMAGE_FALLSMALL("damage.fallsmall"), ELYTRA_LOOP("elytra.loop"), GAME_PLAYER_ATTACK_NODAMAGE("game.player.attack.nodamage"), GAME_PLAYER_HURT("game.player.hurt"), GAME_PLAYER_DIE("game.player.die"), DIG_CLOTH("dig.cloth"), DIG_GRASS("dig.grass"), DIG_GRAVEL("dig.gravel"), DIG_SAND("dig.sand"), DIG_SNOW("dig.snow"), DIG_STONE("dig.stone"), DIG_WOOD("dig.wood"), TILE_PISTON_IN("tile.piston.in"), TILE_PISTON_OUT("tile.piston.out"), FIRE_FIRE("fire.fire"), FIRE_IGNITE("fire.ignite"), LEASHKNOT_BREAK("leashknot.break"), LEASHKNOT_PLACE("leashknot.place"), FIREWORK_BLAST("firework.blast"), FIREWORK_LARGE_BLAST("firework.large_blast"), FIREWORK_LAUNCH("firework.launch"), FIREWORK_SHOOT("firework.shoot"), FIREWORK_TWINKLE("firework.twinkle"), LIQUID_LAVA("liquid.lava"), LIQUID_LAVAPOP("liquid.lavapop"), LIQUID_WATER("liquid.water"), MINECART_BASE("minecart.base"), MINECART_INSIDE("minecart.inside"), MOB_ARMOR_STAND_BREAK("mob.armor_stand.break"), MOB_ARMOR_STAND_HIT("mob.armor_stand.hit"), MOB_ARMOR_STAND_LAND("mob.armor_stand.land"), MOB_ARMOR_STAND_PLACE("mob.armor_stand.place"), MOB_BAT_DEATH("mob.bat.death"), MOB_BAT_HURT("mob.bat.hurt"), MOB_BAT_IDLE("mob.bat.idle"), MOB_BAT_TAKEOFF("mob.bat.takeoff"), MOB_BLAZE_BREATHE("mob.blaze.breathe"), MOB_BLAZE_DEATH("mob.blaze.death"), MOB_BLAZE_HIT("mob.blaze.hit"), MOB_BLAZE_SHOOT("mob.blaze.shoot"), MOB_CHICKEN_HURT("mob.chicken.hurt"), MOB_CHICKEN_PLOP("mob.chicken.plop"), MOB_CHICKEN_SAY("mob.chicken.say"), MOB_CHICKEN_STEP("mob.chicken.step"), MOB_COW_HURT("mob.cow.hurt"), MOB_COW_SAY("mob.cow.say"), MOB_COW_STEP("mob.cow.step"), MOB_COW_MILK("mob.cow.milk"), MOB_CREEPER_DEATH("mob.creeper.death"), MOB_CREEPER_SAY("mob.creeper.say"), MOB_ENDERMEN_DEATH("mob.endermen.death"), MOB_ENDERMEN_HIT("mob.endermen.hit"), MOB_ENDERMEN_IDLE("mob.endermen.idle"), MOB_ENDERMEN_PORTAL("mob.endermen.portal"), MOB_ENDERMEN_SCREAM("mob.endermen.scream"), MOB_ENDERMEN_STARE("mob.endermen.stare"), MOB_ENDERDRAGON_DEATH("mob.enderdragon.death"), MOB_ENDERDRAGON_HIT("mob.enderdragon.hit"), MOB_ENDERDRAGON_FLAP("mob.enderdragon.flap"), MOB_ENDERDRAGON_GROWL("mob.enderdragon.growl"), MOB_GHAST_AFFECTIONATE_SCREAM("mob.ghast.affectionate_scream"), MOB_GHAST_CHARGE("mob.ghast.charge"), MOB_GHAST_DEATH("mob.ghast.death"), MOB_GHAST_FIREBALL("mob.ghast.fireball"), MOB_GHAST_MOAN("mob.ghast.moan"), MOB_GHAST_SCREAM("mob.ghast.scream"), MOB_GUARDIAN_AMBIENT("mob.guardian.ambient"), MOB_GUARDIAN_ATTACK_LOOP("mob.guardian.attack_loop"), MOB_ELDERGUARDIAN_CURSE("mob.elderguardian.curse"), MOB_ELDERGUARDIAN_DEATH("mob.elderguardian.death"), MOB_ELDERGUARDIAN_HIT("mob.elderguardian.hit"), MOB_ELDERGUARDIAN_IDLE("mob.elderguardian.idle"), MOB_GUARDIAN_FLOP("mob.guardian.flop"), MOB_GUARDIAN_DEATH("mob.guardian.death"), MOB_GUARDIAN_HIT("mob.guardian.hit"), MOB_GUARDIAN_LAND_DEATH("mob.guardian.land_death"), MOB_GUARDIAN_LAND_HIT("mob.guardian.land_hit"), MOB_GUARDIAN_LAND_IDLE("mob.guardian.land_idle"), MOB_LLAMA_ANGRY("mob.llama.angry"), MOB_LLAMA_DEATH("mob.llama.death"), MOB_LLAMA_IDLE("mob.llama.idle"), MOB_LLAMA_SPIT("mob.llama.spit"), MOB_LLAMA_HURT("mob.llama.hurt"), MOB_LLAMA_EAT("mob.llama.eat"), MOB_LLAMA_STEP("mob.llama.step"), MOB_LLAMA_SWAG("mob.llama.swag"), MOB_HORSE_ANGRY("mob.horse.angry"), MOB_HORSE_ARMOR("mob.horse.armor"), MOB_HORSE_BREATHE("mob.horse.breathe"), MOB_HORSE_DEATH("mob.horse.death"), MOB_HORSE_DONKEY_ANGRY("mob.horse.donkey.angry"), MOB_HORSE_DONKEY_DEATH("mob.horse.donkey.death"), MOB_HORSE_DONKEY_HIT("mob.horse.donkey.hit"), MOB_HORSE_DONKEY_IDLE("mob.horse.donkey.idle"), MOB_HORSE_EAT("mob.horse.eat"), MOB_HORSE_GALLOP("mob.horse.gallop"), MOB_HORSE_HIT("mob.horse.hit"), MOB_HORSE_IDLE("mob.horse.idle"), MOB_HORSE_JUMP("mob.horse.jump"), MOB_HORSE_LAND("mob.horse.land"), MOB_HORSE_LEATHER("mob.horse.leather"), MOB_HORSE_SKELETON_DEATH("mob.horse.skeleton.death"), MOB_HORSE_SKELETON_HIT("mob.horse.skeleton.hit"), MOB_HORSE_SKELETON_IDLE("mob.horse.skeleton.idle"), MOB_HORSE_SOFT("mob.horse.soft"), MOB_HORSE_WOOD("mob.horse.wood"), MOB_HORSE_ZOMBIE_DEATH("mob.horse.zombie.death"), MOB_HORSE_ZOMBIE_HIT("mob.horse.zombie.hit"), MOB_HORSE_ZOMBIE_IDLE("mob.horse.zombie.idle"), MOB_HUSK_AMBIENT("mob.husk.ambient"), MOB_HUSK_DEATH("mob.husk.death"), MOB_HUSK_HURT("mob.husk.hurt"), MOB_HUSK_STEP("mob.husk.step"), MOB_IRONGOLEM_THROW("mob.irongolem.throw"), MOB_IRONGOLEM_DEATH("mob.irongolem.death"), MOB_IRONGOLEM_HIT("mob.irongolem.hit"), MOB_IRONGOLEM_WALK("mob.irongolem.walk"), MOB_SHULKER_AMBIENT("mob.shulker.ambient"), MOB_SHULKER_CLOSE("mob.shulker.close"), MOB_SHULKER_DEATH("mob.shulker.death"), MOB_SHULKER_CLOSE_HURT("mob.shulker.close.hurt"), MOB_SHULKER_HURT("mob.shulker.hurt"), MOB_SHULKER_OPEN("mob.shulker.open"), MOB_SHULKER_SHOOT("mob.shulker.shoot"), MOB_SHULKER_TELEPORT("mob.shulker.teleport"), MOB_SHULKER_BULLET_HIT("mob.shulker.bullet.hit"), MOB_MAGMACUBE_BIG("mob.magmacube.big"), MOB_MAGMACUBE_JUMP("mob.magmacube.jump"), MOB_MAGMACUBE_SMALL("mob.magmacube.small"), MOB_PARROT_IDLE("mob.parrot.idle"), MOB_PARROT_HURT("mob.parrot.hurt"), MOB_PARROT_DEATH("mob.parrot.death"), MOB_PARROT_STEP("mob.parrot.step"), MOB_PARROT_EAT("mob.parrot.eat"), MOB_PARROT_FLY("mob.parrot.fly"), MOB_PIG_DEATH("mob.pig.death"), MOB_PIG_BOOST("mob.pig.boost"), MOB_PIG_SAY("mob.pig.say"), MOB_PIG_STEP("mob.pig.step"), MOB_RABBIT_HURT("mob.rabbit.hurt"), MOB_RABBIT_IDLE("mob.rabbit.idle"), MOB_RABBIT_HOP("mob.rabbit.hop"), MOB_RABBIT_DEATH("mob.rabbit.death"), MOB_SHEEP_SAY("mob.sheep.say"), MOB_SHEEP_SHEAR("mob.sheep.shear"), MOB_SHEEP_STEP("mob.sheep.step"), MOB_SILVERFISH_HIT("mob.silverfish.hit"), MOB_SILVERFISH_KILL("mob.silverfish.kill"), MOB_SILVERFISH_SAY("mob.silverfish.say"), MOB_SILVERFISH_STEP("mob.silverfish.step"), MOB_ENDERMITE_HIT("mob.endermite.hit"), MOB_ENDERMITE_KILL("mob.endermite.kill"), MOB_ENDERMITE_SAY("mob.endermite.say"), MOB_ENDERMITE_STEP("mob.endermite.step"), MOB_SKELETON_DEATH("mob.skeleton.death"), MOB_SKELETON_HURT("mob.skeleton.hurt"), MOB_SKELETON_SAY("mob.skeleton.say"), MOB_SKELETON_STEP("mob.skeleton.step"), MOB_SLIME_BIG("mob.slime.big"), MOB_SLIME_SMALL("mob.slime.small"), MOB_SLIME_ATTACK("mob.slime.attack"), MOB_SLIME_DEATH("mob.slime.death"), MOB_SLIME_HURT("mob.slime.hurt"), MOB_SLIME_JUMP("mob.slime.jump"), MOB_SLIME_SQUISH("mob.slime.squish"), MOB_SNOWGOLEM_DEATH("mob.snowgolem.death"), MOB_SNOWGOLEM_HURT("mob.snowgolem.hurt"), MOB_SNOWGOLEM_SHOOT("mob.snowgolem.shoot"), MOB_SPIDER_DEATH("mob.spider.death"), MOB_SPIDER_SAY("mob.spider.say"), MOB_SPIDER_STEP("mob.spider.step"), MOB_SQUID_AMBIENT("mob.squid.ambient"), MOB_SQUID_DEATH("mob.squid.death"), MOB_SQUID_HURT("mob.squid.hurt"), MOB_STRAY_AMBIENT("mob.stray.ambient"), MOB_STRAY_DEATH("mob.stray.death"), MOB_STRAY_HURT("mob.stray.hurt"), MOB_STRAY_STEP("mob.stray.step"), MOB_VILLAGER_DEATH("mob.villager.death"), MOB_VILLAGER_HAGGLE("mob.villager.haggle"), MOB_VILLAGER_HIT("mob.villager.hit"), MOB_VILLAGER_IDLE("mob.villager.idle"), MOB_VILLAGER_NO("mob.villager.no"), MOB_VILLAGER_YES("mob.villager.yes"), MOB_VINDICATOR_DEATH("mob.vindicator.death"), MOB_VINDICATOR_HURT("mob.vindicator.hurt"), MOB_VINDICATOR_IDLE("mob.vindicator.idle"), MOB_EVOCATION_FANGS_ATTACK("mob.evocation_fangs.attack"), MOB_EVOCATION_ILLAGER_AMBIENT("mob.evocation_illager.ambient"), MOB_EVOCATION_ILLAGER_CAST_SPELL("mob.evocation_illager.cast_spell"), MOB_EVOCATION_ILLAGER_DEATH("mob.evocation_illager.death"), MOB_EVOCATION_ILLAGER_HURT("mob.evocation_illager.hurt"), MOB_EVOCATION_ILLAGER_PREPARE_ATTACK("mob.evocation_illager.prepare_attack"), MOB_EVOCATION_ILLAGER_PREPARE_SUMMON("mob.evocation_illager.prepare_summon"), MOB_EVOCATION_ILLAGER_PREPARE_WOLOLO("mob.evocation_illager.prepare_wololo"), MOB_VEX_AMBIENT("mob.vex.ambient"), MOB_VEX_DEATH("mob.vex.death"), MOB_VEX_HURT("mob.vex.hurt"), MOB_VEX_CHARGE("mob.vex.charge"), MOB_WITCH_AMBIENT("mob.witch.ambient"), MOB_WITCH_DEATH("mob.witch.death"), MOB_WITCH_HURT("mob.witch.hurt"), MOB_WITCH_DRINK("mob.witch.drink"), MOB_WITCH_THROW("mob.witch.throw"), MOB_WITHER_AMBIENT("mob.wither.ambient"), MOB_WITHER_BREAK_BLOCK("mob.wither.break_block"), MOB_WITHER_DEATH("mob.wither.death"), MOB_WITHER_HURT("mob.wither.hurt"), MOB_WITHER_SHOOT("mob.wither.shoot"), MOB_WITHER_SPAWN("mob.wither.spawn"), MOB_WOLF_BARK("mob.wolf.bark"), MOB_WOLF_DEATH("mob.wolf.death"), MOB_WOLF_GROWL("mob.wolf.growl"), MOB_WOLF_HURT("mob.wolf.hurt"), MOB_WOLF_PANTING("mob.wolf.panting"), MOB_WOLF_SHAKE("mob.wolf.shake"), MOB_WOLF_STEP("mob.wolf.step"), MOB_WOLF_WHINE("mob.wolf.whine"), MOB_CAT_HISS("mob.cat.hiss"), MOB_CAT_HIT("mob.cat.hit"), MOB_CAT_MEOW("mob.cat.meow"), MOB_CAT_PURR("mob.cat.purr"), MOB_CAT_PURREOW("mob.cat.purreow"), MOB_POLARBEAR_BABY_IDLE("mob.polarbear_baby.idle"), MOB_POLARBEAR_IDLE("mob.polarbear.idle"), MOB_POLARBEAR_STEP("mob.polarbear.step"), MOB_POLARBEAR_WARNING("mob.polarbear.warning"), MOB_POLARBEAR_HURT("mob.polarbear.hurt"), MOB_POLARBEAR_DEATH("mob.polarbear.death"), MOB_ZOMBIE_DEATH("mob.zombie.death"), MOB_ZOMBIE_HURT("mob.zombie.hurt"), MOB_ZOMBIE_REMEDY("mob.zombie.remedy"), MOB_ZOMBIE_UNFECT("mob.zombie.unfect"), MOB_ZOMBIE_SAY("mob.zombie.say"), MOB_ZOMBIE_STEP("mob.zombie.step"), MOB_ZOMBIE_WOOD("mob.zombie.wood"), MOB_ZOMBIE_WOODBREAK("mob.zombie.woodbreak"), MOB_ZOMBIEPIG_ZPIG("mob.zombiepig.zpig"), MOB_ZOMBIEPIG_ZPIGANGRY("mob.zombiepig.zpigangry"), MOB_ZOMBIEPIG_ZPIGDEATH("mob.zombiepig.zpigdeath"), MOB_ZOMBIEPIG_ZPIGHURT("mob.zombiepig.zpighurt"), MOB_ZOMBIE_VILLAGER_SAY("mob.zombie_villager.say"), MOB_ZOMBIE_VILLAGER_DEATH("mob.zombie_villager.death"), MOB_ZOMBIE_VILLAGER_HURT("mob.zombie_villager.hurt"), NOTE_BASS("note.bass"), NOTE_BASSATTACK("note.bassattack"), NOTE_BD("note.bd"), NOTE_HARP("note.harp"), NOTE_HAT("note.hat"), NOTE_PLING("note.pling"), NOTE_SNARE("note.snare"), PORTAL_PORTAL("portal.portal"), PORTAL_TRAVEL("portal.travel"), PORTAL_TRIGGER("portal.trigger"), RANDOM_ANVIL_BREAK("random.anvil_break"), RANDOM_ANVIL_LAND("random.anvil_land"), RANDOM_ANVIL_USE("random.anvil_use"), RANDOM_BOW("random.bow"), RANDOM_BOWHIT("random.bowhit"), RANDOM_BREAK("random.break"), RANDOM_BURP("random.burp"), RANDOM_CHESTCLOSED("random.chestclosed"), RANDOM_CHESTOPEN("random.chestopen"), RANDOM_SHULKERBOXCLOSED("random.shulkerboxclosed"), RANDOM_SHULKERBOXOPEN("random.shulkerboxopen"), RANDOM_CLICK("random.click"), RANDOM_DOOR_CLOSE("random.door_close"), RANDOM_DOOR_OPEN("random.door_open"), RANDOM_DRINK("random.drink"), RANDOM_EAT("random.eat"), RANDOM_EXPLODE("random.explode"), RANDOM_FIZZ("random.fizz"), RANDOM_FUSE("random.fuse"), RANDOM_GLASS("random.glass"), RANDOM_LEVELUP("random.levelup"), RANDOM_ORB("random.orb"), RANDOM_POP("random.pop"), RANDOM_POP2("random.pop2"), RANDOM_SPLASH("random.splash"), RANDOM_SWIM("random.swim"), RANDOM_HURT("random.hurt"), RANDOM_TOAST("random.toast"), RANDOM_TOTEM("random.totem"), CAMERA_TAKE_PICTURE("camera.take_picture"), USE_LADDER("use.ladder"), HIT_LADDER("hit.ladder"), FALL_LADDER("fall.ladder"), STEP_LADDER("step.ladder"), USE_CLOTH("use.cloth"), HIT_CLOTH("hit.cloth"), FALL_CLOTH("fall.cloth"), STEP_CLOTH("step.cloth"), USE_GRASS("use.grass"), HIT_GRASS("hit.grass"), FALL_GRASS("fall.grass"), STEP_GRASS("step.grass"), USE_GRAVEL("use.gravel"), HIT_GRAVEL("hit.gravel"), FALL_GRAVEL("fall.gravel"), STEP_GRAVEL("step.gravel"), USE_SAND("use.sand"), HIT_SAND("hit.sand"), FALL_SAND("fall.sand"), STEP_SAND("step.sand"), USE_SLIME("use.slime"), HIT_SLIME("hit.slime"), FALL_SLIME("fall.slime"), STEP_SLIME("step.slime"), USE_SNOW("use.snow"), HIT_SNOW("hit.snow"), FALL_SNOW("fall.snow"), STEP_SNOW("step.snow"), USE_STONE("use.stone"), HIT_STONE("hit.stone"), FALL_STONE("fall.stone"), STEP_STONE("step.stone"), USE_WOOD("use.wood"), HIT_WOOD("hit.wood"), FALL_WOOD("fall.wood"), STEP_WOOD("step.wood"), JUMP_CLOTH("jump.cloth"), JUMP_GRASS("jump.grass"), JUMP_GRAVEL("jump.gravel"), JUMP_SAND("jump.sand"), JUMP_SNOW("jump.snow"), JUMP_STONE("jump.stone"), JUMP_WOOD("jump.wood"), JUMP_SLIME("jump.slime"), LAND_CLOTH("land.cloth"), LAND_GRASS("land.grass"), LAND_GRAVEL("land.gravel"), LAND_SAND("land.sand"), LAND_SNOW("land.snow"), LAND_STONE("land.stone"), LAND_WOOD("land.wood"), LAND_SLIME("land.slime"), VR_STUTTERTURN("vr.stutterturn"), RECORD_13("record.13"), RECORD_CAT("record.cat"), RECORD_BLOCKS("record.blocks"), RECORD_CHIRP("record.chirp"), RECORD_FAR("record.far"), RECORD_MALL("record.mall"), RECORD_MELLOHI("record.mellohi"), RECORD_STAL("record.stal"), RECORD_STRAD("record.strad"), RECORD_WARD("record.ward"), RECORD_11("record.11"), RECORD_WAIT("record.wait"), MUSIC_MENU("music.menu"), MUSIC_GAME("music.game"), MUSIC_GAME_CREATIVE("music.game.creative"), MUSIC_GAME_END("music.game.end"), MUSIC_GAME_ENDBOSS("music.game.endboss"), MUSIC_GAME_NETHER("music.game.nether"), MUSIC_GAME_CREDITS("music.game.credits"); private final String sound; Sound(String sound) { this.sound = sound; } public String getSound() { return this.sound; } }
15,915
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
ChunkPosition.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/ChunkPosition.java
package cn.nukkit.level; import cn.nukkit.math.MathHelper; import cn.nukkit.math.Vector3; /** * Author: Adam Matthew * <p> * Nukkit Project */ public class ChunkPosition { public final int x; public final int y; public final int z; public ChunkPosition(int i, int j, int k) { this.x = i; this.y = j; this.z = k; } public ChunkPosition(Vector3 vec3d) { this(MathHelper.floor(vec3d.x), MathHelper.floor(vec3d.y), MathHelper.floor(vec3d.z)); } @Override public boolean equals(Object object) { if (!(object instanceof ChunkPosition)) { return false; } else { ChunkPosition chunkposition = (ChunkPosition) object; return chunkposition.x == this.x && chunkposition.y == this.y && chunkposition.z == this.z; } } @Override public int hashCode() { return this.x * 8976890 + this.y * 981131 + this.z; } }
959
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
MovingObjectPosition.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/MovingObjectPosition.java
package cn.nukkit.level; import cn.nukkit.entity.Entity; import cn.nukkit.math.Vector3; /** * author: MagicDroidX * Nukkit Project */ public class MovingObjectPosition { /** * 0 = block, 1 = entity */ public int typeOfHit; public int blockX; public int blockY; public int blockZ; /** * Which side was hit. If its -1 then it went the full length of the ray trace. * Bottom = 0, Top = 1, East = 2, West = 3, North = 4, South = 5. */ public int sideHit; public Vector3 hitVector; public Entity entityHit; public static MovingObjectPosition fromBlock(int x, int y, int z, int side, Vector3 hitVector) { MovingObjectPosition objectPosition = new MovingObjectPosition(); objectPosition.typeOfHit = 0; objectPosition.blockX = x; objectPosition.blockY = y; objectPosition.blockZ = z; objectPosition.hitVector = new Vector3(hitVector.x, hitVector.y, hitVector.z); return objectPosition; } public static MovingObjectPosition fromEntity(Entity entity) { MovingObjectPosition objectPosition = new MovingObjectPosition(); objectPosition.typeOfHit = 1; objectPosition.entityHit = entity; objectPosition.hitVector = new Vector3(entity.x, entity.y, entity.z); return objectPosition; } }
1,356
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
GameRules.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/GameRules.java
package cn.nukkit.level; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.BinaryStream; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.EnumMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import static cn.nukkit.level.GameRule.*; @SuppressWarnings({"unchecked"}) public class GameRules { private final EnumMap<GameRule, Value> gameRules = new EnumMap<>(GameRule.class); private boolean stale; private GameRules() { } public static GameRules getDefault() { GameRules gameRules = new GameRules(); gameRules.gameRules.put(COMMAND_BLOCK_OUTPUT, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_DAYLIGHT_CYCLE, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_ENTITY_DROPS, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_FIRE_TICK, new Value(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_MOB_LOOT, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_MOB_SPAWNING, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_TILE_DROPS, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DO_WEATHER_CYCLE, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(DROWNING_DAMAGE, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(FALL_DAMAGE, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(FIRE_DAMAGE, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(KEEP_INVENTORY, new Value<>(Type.BOOLEAN, false)); gameRules.gameRules.put(MOB_GRIEFING, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(NATURAL_REGENERATION, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(PVP, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(SEND_COMMAND_FEEDBACK, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(SHOW_COORDINATES, new Value<>(Type.BOOLEAN, false)); gameRules.gameRules.put(TNT_EXPLODES, new Value<>(Type.BOOLEAN, true)); gameRules.gameRules.put(SHOW_DEATH_MESSAGE, new Value<>(Type.BOOLEAN, true)); return gameRules; } public Map<GameRule, Value> getGameRules() { return ImmutableMap.copyOf(gameRules); } public boolean isStale() { return stale; } public void refresh() { stale = false; } public void setGameRule(GameRule gameRule, boolean value) { if (!gameRules.containsKey(gameRule)) { throw new IllegalArgumentException("Gamerule does not exist"); } gameRules.get(gameRule).setValue(value, Type.BOOLEAN); stale = true; } public void setGameRule(GameRule gameRule, int value) { if (!gameRules.containsKey(gameRule)) { throw new IllegalArgumentException("Gamerule does not exist"); } gameRules.get(gameRule).setValue(value, Type.INTEGER); stale = true; } public void setGameRule(GameRule gameRule, float value) { if (!gameRules.containsKey(gameRule)) { throw new IllegalArgumentException("Gamerule does not exist"); } gameRules.get(gameRule).setValue(value, Type.FLOAT); stale = true; } public void setGameRules(GameRule gameRule, String value) throws IllegalArgumentException { Preconditions.checkNotNull(gameRule, "gameRule"); Preconditions.checkNotNull(value, "value"); switch (getGameRuleType(gameRule)) { case BOOLEAN: if (value.equalsIgnoreCase("true")) { setGameRule(gameRule, true); } else if (value.equalsIgnoreCase("false")) { setGameRule(gameRule, false); } else { throw new IllegalArgumentException("Was not a boolean"); } break; case INTEGER: setGameRule(gameRule, Integer.parseInt(value)); break; case FLOAT: setGameRule(gameRule, Float.parseFloat(value)); } } public boolean getBoolean(GameRule gameRule) { return gameRules.get(gameRule).getValueAsBoolean(); } public int getInteger(GameRule gameRule) { Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).getValueAsInteger(); } public float getFloat(GameRule gameRule) { Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).getValueAsFloat(); } public String getString(GameRule gameRule) { Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).value.toString(); } public Type getGameRuleType(GameRule gameRule) { Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).getType(); } public boolean hasRule(GameRule gameRule) { return gameRules.containsKey(gameRule); } public GameRule[] getRules() { return gameRules.keySet().toArray(new GameRule[gameRules.size()]); } // TODO: This needs to be moved out since there is not a separate compound tag in the LevelDB format for Game Rules. public CompoundTag writeNBT() { CompoundTag nbt = new CompoundTag(); for (Entry<GameRule, Value> entry : gameRules.entrySet()) { nbt.putString(entry.getKey().getName(), entry.getValue().value.toString()); } return nbt; } public void readNBT(CompoundTag nbt) { Preconditions.checkNotNull(nbt); for (String key : nbt.getTags().keySet()) { Optional<GameRule> gameRule = GameRule.parseString(key); if (!gameRule.isPresent()) { continue; } setGameRules(gameRule.get(), nbt.getString(key)); } } public enum Type { UNKNOWN { @Override void write(BinaryStream pk, Value value) { } }, BOOLEAN { @Override void write(BinaryStream pk, Value value) { pk.putBoolean(value.getValueAsBoolean()); } }, INTEGER { @Override void write(BinaryStream pk, Value value) { pk.putUnsignedVarInt(value.getValueAsInteger()); } }, FLOAT { @Override void write(BinaryStream pk, Value value) { pk.putLFloat(value.getValueAsFloat()); } }; abstract void write(BinaryStream pk, Value value); } public static class Value<T> { private final Type type; private T value; public Value(Type type, T value) { this.type = type; this.value = value; } private void setValue(T value, Type type) { if (this.type != type) { throw new UnsupportedOperationException("Rule not of type " + type.name().toLowerCase()); } this.value = value; } public Type getType() { return type; } private boolean getValueAsBoolean() { if (type != Type.BOOLEAN) { throw new UnsupportedOperationException("Rule not of type boolean"); } return (Boolean) value; } private int getValueAsInteger() { if (type != Type.INTEGER) { throw new UnsupportedOperationException("Rule not of type integer"); } return (Integer) value; } private float getValueAsFloat() { if (type != Type.FLOAT) { throw new UnsupportedOperationException("Rule not of type float"); } return (Float) value; } public void write(BinaryStream pk) { pk.putUnsignedVarInt(type.ordinal()); type.write(pk, this); } } }
8,057
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
SimpleChunkManager.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/SimpleChunkManager.java
package cn.nukkit.level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; /** * author: MagicDroidX * Nukkit Project */ public class SimpleChunkManager implements ChunkManager { protected Long2ObjectOpenHashMap<FullChunk> chunks = new Long2ObjectOpenHashMap<>(); protected final long seed; public SimpleChunkManager(long seed) { this.seed = seed; } @Override public int getBlockIdAt(int x, int y, int z) { FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { return chunk.getBlockId(x & 0xf, y & 0xff, z & 0xf); } return 0; } @Override public void setBlockIdAt(int x, int y, int z, int id) { FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { chunk.setBlockId(x & 0xf, y & 0xff, z & 0xf, id); } } @Override public int getBlockDataAt(int x, int y, int z) { FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { return chunk.getBlockData(x & 0xf, y & 0xff, z & 0xf); } return 0; } @Override public void setBlockDataAt(int x, int y, int z, int data) { FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { chunk.setBlockData(x & 0xf, y & 0xff, z & 0xf, data); } } @Override public BaseFullChunk getChunk(int chunkX, int chunkZ) { long index = Level.chunkHash(chunkX, chunkZ); return this.chunks.containsKey(index) ? (BaseFullChunk) this.chunks.get(index) : null; } @Override public void setChunk(int chunkX, int chunkZ) { this.setChunk(chunkX, chunkZ, null); } @Override public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk) { if (chunk == null) { this.chunks.remove(Level.chunkHash(chunkX, chunkZ)); return; } this.chunks.put(Level.chunkHash(chunkX, chunkZ), chunk); } public void cleanChunks() { this.chunks.clear(); } @Override public long getSeed() { return seed; } }
2,245
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z