Search in sources :

Example 26 with Vector3f

use of org.joml.Vector3f in project chunkstories by Hugobros3.

the class VoxelModelsStore method readBlockModel.

private void readBlockModel(Asset asset) {
    logger().debug("Loading custom models file : " + asset);
    try {
        /*FileReader fileReader = new FileReader(voxelModelFile);*/
        Reader fileReader = asset.reader();
        BufferedReader reader = new BufferedReader(fileReader);
        String line = "";
        int ln = 0;
        String voxelModelName = null;
        List<float[]> verticesTemp = new ArrayList<float[]>();
        List<float[]> texcoordsTemp = new ArrayList<float[]>();
        List<float[]> normalsTemp = new ArrayList<float[]>();
        List<Byte> extrasTemps = new ArrayList<Byte>();
        List<boolean[]> cullingTemp = new ArrayList<boolean[]>();
        List<String> texturesNamesTemp = new ArrayList<String>();
        List<Integer> texturesOffsetsTemp = new ArrayList<Integer>();
        String currentTexture = "_top";
        boolean[] currentCull = new boolean[6];
        float jitterX = 0;
        float jitterY = 0;
        float jitterZ = 0;
        int verticesCounter = 0;
        while ((line = reader.readLine()) != null) {
            line = line.replace("\t", "");
            if (line.startsWith("#")) {
            // It's a comment, ignore.
            } else {
                if (voxelModelName == null && !line.equals("")) {
                    voxelModelName = asset.getName().substring(asset.getName().lastIndexOf("/") + 1).replace(".model", "");
                    if (!line.equals("default"))
                        voxelModelName += "." + line;
                    // Textures calculator
                    currentTexture = "_top";
                } else if (line.startsWith("end")) {
                    if (voxelModelName != null) {
                        // Security:
                        if (verticesTemp.size() % 3 != 0) {
                            System.out.println(voxelModelName + " -> " + verticesTemp.size());
                            System.exit(-1);
                        }
                        // Add last used texture
                        texturesNamesTemp.add(currentTexture);
                        texturesOffsetsTemp.add(verticesTemp.size());
                        // Build list of them with offsets
                        String[] texturesNames = new String[texturesNamesTemp.size()];
                        int[] texturesOffsets = new int[texturesNamesTemp.size()];
                        int indexInTextures = 0;
                        for (String textureName : texturesNamesTemp) {
                            texturesNames[indexInTextures] = textureName;
                            texturesOffsets[indexInTextures] = texturesOffsetsTemp.get(indexInTextures);
                            indexInTextures++;
                        }
                        float[] vertices = new float[verticesTemp.size() * 3];
                        float[] texCoords = new float[verticesTemp.size() * 2];
                        float[] normals = new float[verticesTemp.size() * 3];
                        byte[] extras = new byte[extrasTemps.size()];
                        if (verticesTemp.size() != extrasTemps.size()) {
                            System.out.println("FUCK OFF" + verticesTemp.size() + "+" + extrasTemps.size());
                            System.exit(-111);
                        }
                        boolean[][] culling = new boolean[verticesTemp.size()][6];
                        for (int i = 0; i < verticesTemp.size(); i++) {
                            vertices[i * 3 + 0] = verticesTemp.get(i)[0];
                            vertices[i * 3 + 1] = verticesTemp.get(i)[1];
                            vertices[i * 3 + 2] = verticesTemp.get(i)[2];
                            texCoords[i * 2 + 0] = texcoordsTemp.get(i)[0];
                            texCoords[i * 2 + 1] = texcoordsTemp.get(i)[1];
                            normals[i * 3 + 0] = normalsTemp.get(i)[0];
                            normals[i * 3 + 1] = normalsTemp.get(i)[1];
                            normals[i * 3 + 2] = normalsTemp.get(i)[2];
                            extras[i] = extrasTemps.get(i);
                        }
                        for (int i = 0; i < verticesTemp.size() / 3; i++) {
                            culling[i] = cullingTemp.get(i);
                        }
                        CustomVoxelModel voxelModel = new CustomVoxelModel(this, voxelModelName, vertices, texCoords, texturesNames, texturesOffsets, normals, extras, culling, jitterX, jitterY, jitterZ);
                        models.put(voxelModelName, voxelModel);
                        // Resets data accumulators
                        verticesTemp.clear();
                        texcoordsTemp.clear();
                        normalsTemp.clear();
                        cullingTemp.clear();
                        extrasTemps.clear();
                        // Resets textures
                        texturesNamesTemp.clear();
                        texturesOffsetsTemp.clear();
                        // Resets culling engine
                        currentCull = new boolean[6];
                        // Reset fields
                        jitterX = 0;
                        jitterY = 0;
                        jitterZ = 0;
                    } else
                        logger().warn("Parse error in asset " + asset + ", line " + ln + ", unexpected 'end' token.");
                    voxelModelName = null;
                } else if (line.startsWith("texture")) {
                    if (voxelModelName == null)
                        continue;
                    String[] splitted = line.split(" ");
                    String newTextureName = splitted[1].replace("\'", "");
                    // It can't crash from here so we can safely add the textures
                    texturesNamesTemp.add(currentTexture);
                    texturesOffsetsTemp.add(verticesTemp.size());
                    currentTexture = newTextureName;
                } else if (line.startsWith("jitter")) {
                    if (voxelModelName == null)
                        continue;
                    String[] splitted = line.split(" ");
                    jitterX = Float.parseFloat(splitted[1]);
                    jitterY = Float.parseFloat(splitted[2]);
                    jitterZ = Float.parseFloat(splitted[3]);
                } else if (line.startsWith("v")) {
                    if (voxelModelName != null) {
                        // System.out.println("vv"+vertices.size());
                        String[] splitted = line.split(" ");
                        String[] vert = splitted[1].split(",");
                        String[] tex = splitted[2].split(",");
                        String[] nor = splitted[3].split(",");
                        verticesTemp.add(new float[] { Float.parseFloat(vert[0]), Float.parseFloat(vert[1]), Float.parseFloat(vert[2]) });
                        texcoordsTemp.add(new float[] { Float.parseFloat(tex[0]), Float.parseFloat(tex[1]) });
                        // Normalizes normal at loading time
                        Vector3f normalizeMe = new Vector3f(Float.parseFloat(nor[0]), Float.parseFloat(nor[1]), Float.parseFloat(nor[2]));
                        normalizeMe.normalize();
                        normalsTemp.add(new float[] { normalizeMe.x(), normalizeMe.y(), normalizeMe.z() });
                        byte extra = 0;
                        if (splitted.length >= 5)
                            extra = Byte.parseByte(splitted[4]);
                        extrasTemps.add(extra);
                        verticesCounter++;
                        if (verticesCounter >= 3) {
                            cullingTemp.add(currentCull);
                            verticesCounter = 0;
                        }
                    } else
                        logger().warn("Parse error in asset " + asset + ", line " + ln + ", unexpected parameter.");
                } else if (line.startsWith("cull")) {
                    currentCull = new boolean[6];
                    for (String face : line.split(" ")) {
                        switch(face) {
                            case "bottom":
                                currentCull[VoxelSide.BOTTOM.ordinal()] = true;
                                break;
                            case "top":
                                currentCull[VoxelSide.TOP.ordinal()] = true;
                                break;
                            case "left":
                                currentCull[VoxelSide.LEFT.ordinal()] = true;
                                break;
                            case "right":
                                currentCull[VoxelSide.RIGHT.ordinal()] = true;
                                break;
                            case "front":
                                currentCull[VoxelSide.FRONT.ordinal()] = true;
                                break;
                            case "back":
                                currentCull[VoxelSide.BACK.ordinal()] = true;
                                break;
                        }
                    }
                } else if (line.startsWith("require")) {
                    if (voxelModelName != null) {
                        String[] splitted = line.split(" ");
                        if (splitted.length == 2) {
                            String toInclude = splitted[1];
                            toInclude = toInclude.replace("~", voxelModelName.contains(".") ? voxelModelName.split("\\.")[0] : voxelModelName);
                            VoxelModel includeMeh = getVoxelModel(toInclude);
                            if (includeMeh != null) {
                                // Iterates over included model
                                for (int i = 0; i < includeMeh.getSizeInVertices(); i++) {
                                    verticesTemp.add(new float[] { includeMeh.getVertices()[i * 3 + 0], includeMeh.getVertices()[i * 3 + 1], includeMeh.getVertices()[i * 3 + 2] });
                                    texcoordsTemp.add(new float[] { includeMeh.getTexCoords()[i * 2 + 0], includeMeh.getTexCoords()[i * 2 + 1] });
                                    normalsTemp.add(new float[] { includeMeh.getNormals()[i * 3 + 0], includeMeh.getNormals()[i * 3 + 1], includeMeh.getNormals()[i * 3 + 2] });
                                    extrasTemps.add(includeMeh.getExtra()[i]);
                                }
                                // TODO it doesn't import their textures settings !
                                for (boolean[] cul : includeMeh.getCulling()) cullingTemp.add(cul);
                            } else
                                logger().warn("Can't require '" + toInclude + "'");
                        }
                    } else
                        logger().warn("Parse error in asset " + asset + ", line " + ln + ", unexpected parameter.");
                }
            }
            ln++;
        }
        // ChunkStoriesLogger.getInstance().log("Debug : Parsed file " + f + " correctly, loading " + loadedBM + " blockmodels.", ChunkStoriesLogger.LogType.GAMEMODE, ChunkStoriesLogger.LogLevel.DEBUG);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : ArrayList(java.util.ArrayList) Reader(java.io.Reader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) VoxelModel(io.xol.chunkstories.api.voxel.models.VoxelModel) Vector3f(org.joml.Vector3f) BufferedReader(java.io.BufferedReader)

Example 27 with Vector3f

use of org.joml.Vector3f in project chunkstories by Hugobros3.

the class ClientParticlesRenderer method spawnParticleAtPositionWithVelocity.

public void spawnParticleAtPositionWithVelocity(String particleTypeName, Vector3dc location, Vector3dc velocity) {
    ParticleTypeHandler particleType = store.getParticleType(particleTypeName);
    if (particleType == null || location == null)
        return;
    ParticleData particleData = particleType.createNew(world, (float) (double) location.x(), (float) (double) location.y(), (float) (double) location.z());
    if (velocity != null && particleData instanceof ParticleDataWithVelocity)
        ((ParticleDataWithVelocity) particleData).setVelocity(new Vector3f((float) velocity.x(), (float) velocity.y(), (float) velocity.z()));
    addParticle(particleType, particleData);
}
Also used : ParticleData(io.xol.chunkstories.api.particles.ParticleTypeHandler.ParticleData) ParticleDataWithVelocity(io.xol.chunkstories.api.particles.ParticleDataWithVelocity) ParticleTypeHandler(io.xol.chunkstories.api.particles.ParticleTypeHandler) Vector3f(org.joml.Vector3f)

Example 28 with Vector3f

use of org.joml.Vector3f in project chunkstories by Hugobros3.

the class BVHAnimation method load.

private void load(InputStream is) {
    bones.clear();
    try {
        BVHTreeBone currentBone = null;
        int readingFrame = 0;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = "";
        boolean readingMotion = false;
        boolean readingDest = false;
        while ((line = reader.readLine()) != null) {
            // We don't want the tabs.
            line = line.replace("\t", "");
            String[] items = line.split(" ");
            if (readingMotion) {
                if (line.startsWith("Frames:")) {
                    frames = Integer.parseInt(items[1]);
                    root.recursiveInitMotion(frames);
                } else if (line.startsWith("Frame Time:"))
                    frameTime = Float.parseFloat(items[2]);
                else {
                    float[] lineData = new float[items.length];
                    // Fill this shit
                    for (int i = 0; i < lineData.length; i++) lineData[i] = Float.parseFloat(items[i]);
                    // System.out.println("lineData : "+lineData.length+" / "+totalChannels);
                    int index = 0;
                    currentBone = root;
                    while (currentBone != null) {
                        if (!currentBone.animationDataLoaded) {
                            // TODO clean that crap up and simply shit
                            for (int i = 0; i < currentBone.channels; i++) {
                                currentBone.animationData[readingFrame][i] = lineData[index];
                                // System.out.println("reading channel "+i+" for bone id"+currentBone.id);
                                index++;
                            }
                        }
                        currentBone.animationDataLoaded = true;
                        boolean hasDoneAllChilds = true;
                        for (BVHTreeBone c : currentBone.childs) {
                            if (!c.animationDataLoaded) {
                                hasDoneAllChilds = false;
                                currentBone = c;
                                break;
                            }
                        }
                        if (hasDoneAllChilds)
                            currentBone = currentBone.parent;
                    }
                    root.recursiveResetFlag();
                    readingFrame++;
                }
            } else {
                if (line.equals("HIERARCHY")) {
                    readingMotion = false;
                } else if (line.startsWith("ROOT")) {
                    final String boneName = items[1];
                    root = new BVHTreeBone(boneName, null, this);
                    currentBone = root;
                    // Add to global bones list
                    bones.put(boneName, root);
                } else if (line.startsWith("{")) {
                // ignore
                } else if (line.startsWith("OFFSET")) {
                    if (readingDest)
                        currentBone.dest = new Vector3f(Float.parseFloat(items[1]), Float.parseFloat(items[2]), Float.parseFloat(items[3]));
                    else
                        currentBone.offset = new Vector3f(Float.parseFloat(items[1]), Float.parseFloat(items[2]), Float.parseFloat(items[3]));
                } else if (line.startsWith("CHANNELS")) {
                    // Currently only support for XYZ POS+ROT and ROT
                    // formats.
                    currentBone.channels = Integer.parseInt(items[1]);
                } else if (line.startsWith("JOINT")) {
                    final String boneName = items[1];
                    BVHTreeBone newBone = new BVHTreeBone(boneName, currentBone, this);
                    currentBone.childs.add(newBone);
                    currentBone = newBone;
                    // Add to global bones list
                    bones.put(boneName, newBone);
                } else if (line.equals("End Site")) {
                    readingDest = true;
                } else if (line.startsWith("}")) {
                    // If we were reading an end site, stop
                    if (readingDest)
                        readingDest = false;
                    else
                        // Else we point to current bone's parent
                        currentBone = currentBone.parent;
                } else if (line.equals("MOTION")) {
                    readingMotion = true;
                }
            }
        }
        reader.close();
    } catch (IOException | NullPointerException e) {
        e.printStackTrace();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Vector3f(org.joml.Vector3f) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 29 with Vector3f

use of org.joml.Vector3f in project Terasology by MovingBlocks.

the class LocationComponentTest method testParentRotatesWorldLocation.

@Test
public void testParentRotatesWorldLocation() {
    LocationComponent parent = giveParent();
    loc.setLocalPosition(pos1);
    parent.setLocalRotation(yawRotation);
    assertEquals(new Vector3f(pos1.z, pos1.y, -pos1.x), loc.getWorldPosition(new Vector3f()), 0.00001f);
}
Also used : Vector3f(org.joml.Vector3f) Test(org.junit.jupiter.api.Test)

Example 30 with Vector3f

use of org.joml.Vector3f in project Terasology by MovingBlocks.

the class LocationComponentTest method testScaleRotateAndOffsetCombineCorrectlyForWorldPosition.

@Test
public void testScaleRotateAndOffsetCombineCorrectlyForWorldPosition() {
    LocationComponent parent = giveParent();
    loc.setLocalPosition(pos1);
    parent.setLocalScale(2.0f);
    parent.setLocalPosition(pos2);
    parent.setLocalRotation(yawRotation);
    assertEquals(new Vector3f(8, 7, 2), loc.getWorldPosition(new Vector3f()), 0.00001f);
}
Also used : Vector3f(org.joml.Vector3f) Test(org.junit.jupiter.api.Test)

Aggregations

Vector3f (org.joml.Vector3f)261 LocationComponent (org.terasology.engine.logic.location.LocationComponent)50 EntityRef (org.terasology.engine.entitySystem.entity.EntityRef)49 Matrix4f (org.joml.Matrix4f)34 Quaternionf (org.joml.Quaternionf)29 Test (org.junit.jupiter.api.Test)20 Vector3i (org.joml.Vector3i)19 ReceiveEvent (org.terasology.engine.entitySystem.event.ReceiveEvent)18 FloatBuffer (java.nio.FloatBuffer)17 ClientComponent (org.terasology.engine.network.ClientComponent)17 ByteBuffer (java.nio.ByteBuffer)16 Vector3fc (org.joml.Vector3fc)15 Command (org.terasology.engine.logic.console.commandSystem.annotations.Command)15 Vector2f (org.joml.Vector2f)13 Vector4f (org.joml.Vector4f)13 ArrayList (java.util.ArrayList)10 HitResult (org.terasology.engine.physics.HitResult)10 IOException (java.io.IOException)8 Test (org.junit.Test)8 VertexResourceBuilder (org.terasology.engine.rendering.assets.mesh.resource.VertexResourceBuilder)8