Package com.ardor3d.renderer

Examples of com.ardor3d.renderer.Camera


     * Initialize pssm pass and scene.
     */
    @Override
    protected void initExample() {
        _canvas.setTitle("Terrain Example");
        final Camera cam = _canvas.getCanvasRenderer().getCamera();
        cam.setLocation(new Vector3(440, 215, 275));
        cam.lookAt(new Vector3(450, 140, 360), Vector3.UNIT_Y);
        cam.setFrustumPerspective(70.0, (float) cam.getWidth() / cam.getHeight(), 1.0f, farPlane);
        final CanvasRenderer canvasRenderer = _canvas.getCanvasRenderer();
        final RenderContext renderContext = canvasRenderer.getRenderContext();
        final Renderer renderer = canvasRenderer.getRenderer();
        GameTaskQueueManager.getManager(renderContext).getQueue(GameTaskQueue.RENDER).enqueue(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                renderer.setBackgroundColor(ColorRGBA.GRAY);
                return null;
            }
        });
        _controlHandle.setMoveSpeed(200);

        setupDefaultStates();

        sphere.getSceneHints().setAllPickingHints(false);
        sphere.getSceneHints().setCullHint(CullHint.Always);
        _root.attachChild(sphere);

        try {
            // Keep a separate camera to be able to freeze terrain update
            terrainCamera = new Camera(cam);

            final int SIZE = 2048;

            final MidPointHeightMapGenerator raw = new MidPointHeightMapGenerator(SIZE, 0.6f);
            raw.setHeightRange(0.2f);
            final float[] heightMap = raw.getHeightData();

            final TerrainDataProvider terrainDataProvider = new ArrayTerrainDataProvider(heightMap, SIZE, new Vector3(
                    1, 300, 1));

            terrain = new TerrainBuilder(terrainDataProvider, terrainCamera).setShowDebugPanels(true).build();

            terrain.setPixelShader(new UrlInputSupplier(ResourceLocatorTool
                    .getClassPathResource(ShadowedTerrainExample.class,
                            "com/ardor3d/extension/terrain/shadowedGeometryClipmapShaderPCF.frag")));
            terrain.reloadShader();

            _root.attachChild(terrain);
        } catch (final Exception e) {
            logger.log(Level.SEVERE, "Problem setting up terrain...", e);
            System.exit(1);
        }

        // Initialize PSSM shadows
        _pssmPass = new ParallelSplitShadowMapPass(light, 1024, 4);
        _pssmPass.setFiltering(Filter.Pcf);
        _pssmPass.setRenderShadowedScene(false);
        _pssmPass.setKeepMainShader(true);
        _pssmPass.setMaxShadowDistance(750); // XXX: Tune this
        // _pssmPass.setMinimumLightDistance(500); // XXX: Tune this
        _pssmPass.setUseSceneTexturing(false);
        _pssmPass.setUseObjectCullFace(false);
        // _pssmPass.setDrawDebug(true);

        final Node occluders = setupOccluders();
        _root.attachChild(occluders);

        // TODO: could we use the shadow variable in scenehints here??
        // Add objects that will get shadowed through overlay render
        _pssmPass.add(occluders);

        // Add terrain in as bounds receiver as well, since it's not in the overlay list
        _pssmPass.addBoundsReceiver(terrain);

        // Add our occluders that will produce shadows
        _pssmPass.addOccluder(occluders);

        // Setup labels for presenting example info.
        final Node textNodes = new Node("Text");
        _root.attachChild(textNodes);
        textNodes.getSceneHints().setRenderBucketType(RenderBucketType.Ortho);
        textNodes.getSceneHints().setLightCombineMode(LightCombineMode.Off);

        final double infoStartY = _canvas.getCanvasRenderer().getCamera().getHeight() / 2;
        for (int i = 0; i < _exampleInfo.length; i++) {
            _exampleInfo[i] = BasicText.createDefaultTextLabel("Text", "", 16);
            _exampleInfo[i].setTranslation(new Vector3(10, infoStartY - i * 20, 0));
            textNodes.attachChild(_exampleInfo[i]);
        }

        textNodes.updateGeometricState(0.0);
        updateText();

        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.U), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                updateTerrain = !updateTerrain;
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ONE), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                _controlHandle.setMoveSpeed(5);
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.TWO), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                _controlHandle.setMoveSpeed(50);
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.THREE), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                _controlHandle.setMoveSpeed(400);
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.FOUR), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                _controlHandle.setMoveSpeed(1000);
                updateText();
            }
        }));

        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.SPACE), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                groundCamera = !groundCamera;
                updateText();
            }
        }));

        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.P), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                if (sphere.getSceneHints().getCullHint() == CullHint.Dynamic) {
                    sphere.getSceneHints().setCullHint(CullHint.Always);
                } else if (sphere.getSceneHints().getCullHint() == CullHint.Always) {
                    sphere.getSceneHints().setCullHint(CullHint.Dynamic);
                }
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.R), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                terrain.getTextureClipmap().setShowDebug(!terrain.getTextureClipmap().isShowDebug());
                terrain.reloadShader();
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.G), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                terrain.reloadShader();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.FIVE), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                terrain.getTextureClipmap().setScale(terrain.getTextureClipmap().getScale() / 2);
                terrain.reloadShader();
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.SIX), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                terrain.getTextureClipmap().setScale(terrain.getTextureClipmap().getScale() * 2);
                terrain.reloadShader();
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.C), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                _pssmPass.setUpdateMainCamera(!_pssmPass.isUpdateMainCamera());
                updateText();
            }
        }));
        _logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
            public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
                final Camera cam = _canvas.getCanvasRenderer().getCamera();
                System.out.println("camera location: " + cam.getLocation());
                System.out.println("camera direction: " + cam.getDirection());
            }
        }));

    }
View Full Code Here


        return ParticleSystem.ParticleType.Point;
    }

    @Override
    public void draw(final Renderer r) {
        final Camera camera = Camera.getCurrentCamera();
        boolean anyAlive = false;
        for (int i = 0; i < _particles.length; i++) {
            final Particle particle = _particles[i];
            if (particle.getStatus() == Particle.Status.Alive) {
                particle.updateVerts(camera);
View Full Code Here

        return ParticleSystem.ParticleType.Line;
    }

    @Override
    public void draw(final Renderer r) {
        final Camera camera = Camera.getCurrentCamera();
        boolean anyAlive = false;
        for (int i = 0; i < _particles.length; i++) {
            final Particle particle = _particles[i];
            if (particle.getStatus() == Particle.Status.Alive) {
                particle.updateVerts(camera);
View Full Code Here

        _particleMesh.getSceneHints().setCastsShadows(false);
    }

    @Override
    public void draw(final Renderer r) {
        final Camera camera = Camera.getCurrentCamera();
        boolean anyAlive = false;
        for (int i = 0; i < _particles.length; i++) {
            final Particle particle = _particles[i];
            if (particle.getStatus() == Particle.Status.Alive) {
                particle.updateVerts(camera);
View Full Code Here

            return;
        }

        // If instructed, check to see if our last frustum check passed
        if (isUpdateOnlyInView()) {
            final Camera cam = _viewCamera != null ? _viewCamera : ContextManager.getCurrentContext()
                    .getCurrentCamera();
            if (cam != null) {
                final int state = cam.getPlaneState();
                final boolean out = cam.contains(particles.getWorldBound()).equals(FrustumIntersect.Outside);
                cam.setPlaneState(state);
                if (out) {
                    return;
                }
            }
        }

        // Add time and unless we have more than precision time passed
        // since last real update, do nothing
        _currentTime += secondsPassed * getSpeed();

        // Check precision passes
        _timePassed = _currentTime - _prevTime;
        if (_timePassed < _precision * getSpeed()) {
            return;
        }

        // We are actually going to do a real update,
        // so this is our new previous time
        _prevTime = _currentTime;

        // Update the current rotation matrix if needed.
        particles.updateRotationMatrix();

        // If we are in the time window where this controller is active
        // (defaults to 0 to Float.MAX_VALUE for ParticleController)
        if (_currentTime >= getMinTime() && _currentTime <= getMaxTime()) {

            // If we are controlling the flow (ie the rate of particle spawning.)
            if (_controlFlow) {
                // Release a number of particles based on release rate,
                // timePassed (already scaled for speed) and variance. This
                // is added to any current value Note this is a double value,
                // so we will keep adding up partial particles

                _releaseParticles += (particles.getReleaseRate() * _timePassed * (1.0 + _releaseVariance
                        * (MathUtils.nextRandomFloat() - 0.5)));

                // Try to create all "whole" particles we have added up
                _particlesToCreate = (int) _releaseParticles;

                // If we have any whole particles, then subtract them from
                // releaseParticles
                if (_particlesToCreate > 0) {
                    _releaseParticles -= _particlesToCreate;
                } else {
                    _particlesToCreate = 0;
                }
            }

            particles.updateInvScale();

            // If we have any influences, prepare them all
            if (influences != null) {
                for (int x = 0; x < influences.size(); x++) {
                    final ParticleInfluence inf = influences.get(x);
                    inf.prepare(particles);
                }
            }

            // Track particle index
            int i = 0;

            // Track whether the whole set of particles is "dead" - if any
            // particles are still alive, this will be set to false
            boolean dead = true;

            // opposite of above boolean, but tracked separately
            boolean anyAlive = false;

            // i is index through all particles
            while (i < particles.getNumParticles()) {
                // Current particle
                final Particle p = particles.getParticle(i);

                // If we have influences and particle is alive
                if (influences != null && p.getStatus() == Particle.Status.Alive) {
                    // Apply each enabled influence to the current particle
                    for (int x = 0; x < influences.size(); x++) {
                        final ParticleInfluence inf = influences.get(x);
                        if (inf.isEnabled()) {
                            inf.apply(_timePassed, p, i);
                        }
                    }
                }

                // Update and check the particle.
                // If this returns true, indicating particle is ready to be
                // reused, we may reuse it. Do so if we are not using
                // control flow, OR we intend to create particles based on
                // control flow count calculated above
                final boolean reuse = p.updateAndCheck(_timePassed);
                if (reuse && (!_controlFlow || _particlesToCreate > 0)) {

                    // Don't recreate the particle if it is dead, and we are clamped
                    if (p.getStatus() == Particle.Status.Dead && getRepeatType() == RepeatType.CLAMP) {
                        ;

                        // We plan to reuse the particle
                    } else {
                        if (_spawnEnabled) {
                            // Not all particles are dead (this one will be reused)
                            dead = false;

                            // If we are doing flow control, decrement
                            // particlesToCreate, since we are about to create
                            // one
                            if (_controlFlow) {
                                _particlesToCreate--;
                            }

                            // Recreate the particle
                            p.recreateParticle(particles.getRandomLifeSpan());
                            p.setStatus(Particle.Status.Alive);
                            // in case of ramp time 0 entries.
                            p.updateAndCheck(0);
                            particles.initParticleLocation(i);
                            particles.resetParticleVelocity(i);
                            p.updateVerts(null);
                        }
                    }

                } else if (!reuse || (_controlFlow && particles.getReleaseRate() > 0)) {
                    // The particle wasn't dead, or we expect more particles
                    // later, so we're not dead!
                    dead = false;
                }

                // Check for living particles so we know when to update our boundings.
                if (p.getStatus() == Particle.Status.Alive) {
                    anyAlive = true;
                }

                // Next particle
                i++;
            }

            // If we are dead, deactivate and tell our listeners
            if (dead) {
                setActive(false);
                if (listeners != null && listeners.size() > 0) {
                    for (final ParticleControllerListener listener : listeners) {
                        listener.onDead(particles);
                    }
                }
            } else {
                // if not dead make sure our particles refresh their vbos, etc.
                final MeshData md = particles.getParticleGeometry().getMeshData();
                md.getVertexCoords().setNeedsRefresh(true);
                md.getColorCoords().setNeedsRefresh(true);
                md.getTextureCoords(0).setNeedsRefresh(true);
            }

            // If we have any live particles and are offscreen, update it
            if (anyAlive) {
                boolean updateMB = true;
                final Camera cam = _viewCamera != null ? _viewCamera
                        : (ContextManager.getCurrentContext() != null ? ContextManager.getCurrentContext()
                                .getCurrentCamera() : null);
                if (cam != null) {
                    final int state = cam.getPlaneState();
                    updateMB = cam.contains(particles.getWorldBound()).equals(FrustumIntersect.Outside);
                    cam.setPlaneState(state);
                }
                if (updateMB) {
                    particles.getParticleGeometry().updateModelBound();
                    particles.updateWorldBoundManually();
                }
View Full Code Here

        // If updating camera is true (can be turned off for debugging), copy from main
        // camera and pack frustum.
        if (_updateMainCamera) {
            // Copy our active camera to our working pssm camera.
            final Camera cam = ContextManager.getCurrentContext().getCurrentCamera();
            _pssmCam.set(cam);

            // Calculate the closest fitting near and far planes.
            if (hasValidBounds) {
                _pssmCam.pack(_receiverBounds);
View Full Code Here

        for (int i = 0; i < 8; i++) {
            BufferUtils.setInBuffer(frustumCorners[i], frustumBoundingBuffer, i);
        }
        frustumBoundingSphere.computeFromPoints(frustumBoundingBuffer);

        final Camera shadowCam = _shadowMapRenderer.getCamera();

        final ReadOnlyVector3 center = frustumBoundingSphere.getCenter();
        final double radius = frustumBoundingSphere.getRadius();

        Vector3 direction = new Vector3();
        final DirectionalLight dl = (DirectionalLight) _light;
        direction = direction.set(dl.getDirection());
        final double distance = Math.max(radius, _minimumLightDistance);

        final Vector3 tmpVec = Vector3.fetchTempInstance();
        tmpVec.set(direction);
        tmpVec.negateLocal();
        tmpVec.multiplyLocal(distance);
        tmpVec.addLocal(center);

        // temporary location
        shadowCam.setLocation(tmpVec);
        shadowCam.lookAt(center, Vector3.UNIT_Y);

        {
            // determine
            final double texelSizeW = (2 * radius) / _shadowMapRenderer.getWidth();
            final double texelSizeH = (2 * radius) / _shadowMapRenderer.getHeight();

            // build a Quaternion from camera axes to move
            final Quaternion q = Quaternion.fetchTempInstance();
            q.fromAxes(shadowCam.getLeft(), shadowCam.getUp(), shadowCam.getDirection());

            // invert to calculate in light space
            final Vector3 lightSpace = q.invert(null).apply(tmpVec, Vector3.fetchTempInstance());

            // snap to nearest texel
            lightSpace.setX(lightSpace.getX() - (lightSpace.getX() % texelSizeW));
            lightSpace.setY(lightSpace.getY() - (lightSpace.getY() % texelSizeH));

            // convert back
            q.apply(lightSpace, tmpVec);
            Vector3.releaseTempInstance(lightSpace);

            Quaternion.releaseTempInstance(q);
        }

        // updated location
        final double x = tmpVec.getX();
        final double y = tmpVec.getY();
        final double z = tmpVec.getZ();
        final double farZ = tmpVec.subtractLocal(center).length() + radius;
        Vector3.releaseTempInstance(tmpVec);

        // set frustum, then location
        shadowCam.setFrustum(1, farZ, -radius, radius, radius, -radius);
        shadowCam.setLocation(x, y, z);
    }
View Full Code Here

     *
     * @param frustumCorners
     * @param center
     */
    private void calculateOptimalLightFrustumOld(final Vector3[] frustumCorners, final ReadOnlyVector3 center) {
        final Camera shadowCam = _shadowMapRenderer.getCamera();

        double distance = _minimumLightDistance;

        final Vector3 tmpVec = Vector3.fetchTempInstance();

        // Update shadow camera from light
        final PointLight pl = (PointLight) _light;

        shadowCam.setLocation(pl.getLocation());

        // Point light at split center
        shadowCam.lookAt(center, Vector3.UNIT_Y);

        // Reset frustum
        distance = center.subtract(shadowCam.getLocation(), tmpVec).length();
        shadowCam.setFrustum(1, distance, -1, 1, 1, -1);

        double fMinX = Double.POSITIVE_INFINITY;
        double fMaxX = Double.NEGATIVE_INFINITY;
        double fMinY = Double.POSITIVE_INFINITY;
        double fMaxY = Double.NEGATIVE_INFINITY;
        double fMinZ = Double.POSITIVE_INFINITY;
        double fMaxZ = Double.NEGATIVE_INFINITY;

        final ReadOnlyMatrix4 lightviewproj = shadowCam.getModelViewProjectionMatrix();

        final Vector4 position = Vector4.fetchTempInstance();
        for (final Vector3 frustumCorner : frustumCorners) {
            position.set(frustumCorner.getX(), frustumCorner.getY(), frustumCorner.getZ(), 1);
            lightviewproj.applyPre(position, position);

            position.setX(position.getX() / position.getW());
            position.setY(position.getY() / position.getW());
            position.setZ(position.getZ());

            fMinX = Math.min(position.getX(), fMinX);
            fMaxX = Math.max(position.getX(), fMaxX);

            fMinY = Math.min(position.getY(), fMinY);
            fMaxY = Math.max(position.getY(), fMaxY);

            fMinZ = Math.min(position.getZ(), fMinZ);
            fMaxZ = Math.max(position.getZ(), fMaxZ);
        }

        double width = 0;
        double height = 0;
        fMinX = clamp(fMinX, -1.0, 1.0);
        fMaxX = clamp(fMaxX, -1.0, 1.0);
        fMinY = clamp(fMinY, -1.0, 1.0);
        fMaxY = clamp(fMaxY, -1.0, 1.0);

        // Make sure the minimum z is at least a specified distance from
        // the target.
        fMinZ = Math.min(fMinZ, distance - _minimumLightDistance);
        fMinZ = Math.max(10.0, fMinZ);

        width = fMinZ * (fMaxX - fMinX) * 0.5;
        height = fMinZ * (fMaxY - fMinY) * 0.5;

        final Vector3 newCenter = Vector3.fetchTempInstance();
        position.set((fMinX + fMaxX) * 0.5, (fMinY + fMaxY) * 0.5, 1.0, 1);
        shadowCam.getModelViewProjectionInverseMatrix().applyPre(position, position);
        position.divideLocal(position.getW());
        newCenter.set(position.getX(), position.getY(), position.getZ());

        shadowCam.lookAt(newCenter, Vector3.UNIT_Y);

        Vector3.releaseTempInstance(newCenter);
        Vector4.releaseTempInstance(position);

        shadowCam.setFrustum(fMinZ, fMaxZ, -width, width, height, -height);
        shadowCam.update();
    }
View Full Code Here

     * @param index
     *            the index
     */
    private void updateTextureMatrix(final int index) {
        // Create a matrix going from light to camera space
        final Camera cam = ContextManager.getCurrentContext().getCurrentCamera();
        _shadowMatrix.set(cam.getModelViewMatrix()).invertLocal();
        _shadowMatrix.multiplyLocal(_shadowMapRenderer.getCamera().getModelViewProjectionMatrix()).multiplyLocal(
                SCALE_BIAS_MATRIX);
        _shadowMapTexture[index].setTextureMatrix(_shadowMatrix);
    }
View Full Code Here

TOP

Related Classes of com.ardor3d.renderer.Camera

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.