Code Monkey home page Code Monkey logo

box2dlights's Introduction

Box2DLights

GitHub Actions Build Status

Latest Version Snapshots

screenshot

Kalle Hameleinen's Box2DLights is a 2D lighting framework that uses box2d for raycasting and OpenGL ES 2.0 for rendering. This library is intended to be used with libgdx.

Try Kalle's game Boxtrix to see the library in action.

Features

  • Arbitrary number of lights
  • Gaussian blurred light maps
  • Point light
  • Cone Light
  • Directional Light
  • Chain Light [New in 1.3]
  • Shadows
  • Dynamic/static/xray light
  • Culling
  • Colored ambient light
  • Gamma corrected colors
  • Handler class to do all the work
  • Query method for testing is point inside of light/shadow

This library offer easy way to add soft dynamic 2d lights to your physic based game. Rendering use libgdx but it would be easy to port this to other frameworks or pure openGl too.

Usage

Box2DLights is also available in Maven Central. Add the following dependency to your libgdx core project:

<dependency>
  <groupId>com.badlogicgames.box2dlights</groupId>
  <artifactId>box2dlights</artifactId>
  <version>1.4</version>
</dependency>

If you use Gradle, add the following dependency to your build.gradle file, in the dependencies block of the core project:

 compile "com.badlogicgames.box2dlights:box2dlights:1.4"

Maintenance Note

Box2dlights was moved from Google Code to Github to make contributing easier. The libgdx team will happily merge pull requests but will not fix bugs or ensure compatibility with the latest libgdx version.

box2dlights's People

Contributors

badlogic avatar c2v4 avatar favu100 avatar fgnm avatar johnnyapol avatar leruaa avatar mobidevelop avatar piotr-j avatar rinold avatar simonit avatar sprucely avatar thechubbypanda avatar tom-ski avatar tskrebe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

box2dlights's Issues

using multiple light layers

Hi, I think it could be a greate thing to be able to use multiple rayHandler (one per layer).
The main loop could be like this:

// render layer 0 (background)
map.render(0);
rayHandler1.updateAndRender();
// render layer 1 (front)
map.render(1);
rayHandler2.updateAndRender();

To achieve this, I think that the light/shadow shader may be disabled when the alpha chanel of a pixel is equal to 0, this way, the shadow of the front layer wont be casted to the back layer anymore.

for an example, see towerfall ascension game, they make use of 2 light layers (the background is not affected by the light on the foreground).

http://www.gamesaktuell.de/screenshots/original/2013/11/towerfall_ascension_2-pc-games.JPG

box2dlights doesnot work with libGDX 1.6.2

Since latest change in libGDX in commit 9036b80...

when using rayHandler.updateAndRender();
it throws weird error: see stacktrace

how to reproduce

  1. Create empty libgdx project using setup app, and make sure to use libgdx 1.6.2
  2. use this source as example:

@xoppa suggested that this might be the problem.

But I am not sure, because no matter the version, method is still there, it is just in a parent class now.

Any idea what this might be?

setActive(false) for Cone Light issue

When I set a PointLight to be inactive through PositionalLight.setActive(false), it doesn't get rendered, as expected. But when I do the same for a cone light, some part of it remains. The effect is as if the light was dimmed, not turned off.
light

As seen in the picture, only one of the lights is active, the one that is separate from the others, to the left; but all the other cone lights don't disappear at all, just get dimmed.

Old issue regarding Ray

I'd like to "re-open" an old issue from Google Code, where a Box2d sensor blocks the ray casting used by box2dLights. The part of the code to return -1 in the callback when the Fixture is a sensor, is still commented out, hence the blockage.

While people could amend the source themselves, they'd have to do so on every release of box2dLights, which is obviously an inconvenience.

Edit: Just to let others know, filters set on the light via setContactFilter() works, but you'll have to set the the appropriate category / group / mask bits, for it work.

Lights over burning with useDiffuseLight(true)

Hi there,

I'm attempting to use box2d lights in conjunction with an OrthogonalTiledMapRenderer and am experiencing issues with lights over burning despite having useDiffuseLight set to true on the RayHandler.

I've had a talk with kalle_h on IRC and he is unsure as to why this would happen, as such I've been directed here ^^

I can provide code as required, here is an example screenshot of the lights over saturating. I would love to get this sorted as it would mean I can use this awesome lighting system in my game, am happy to provide any and all resources required for someone in the know to properly look at this for me!

comparison

Thanks very much for your time,
c0ke

Directional Light has a top and bottom

When using DirectionalLight in a game with panning camera and wide box2d world DirectionalLight is not vertically infinite. It ends at +50y and -50y

Other lights outside this range continue to act as normal.

amygdalascreenshot1432611006922
amygdalascreenshot1432611298333

DirectionalLight extension for "top-down" view

Hi,

I either don't understand the concept or it's not possible right now, but I would like to use the effect of a DirectionalLight to be the sun for a world in a top-down view. Additionally, an argument to set its "position" (I understand this is not a positional light) over the scene would be great, to simulate the transit through of a body like the sun over periods of time.

Thanks.

RayHandler.setAmbientLight() doesn't seem to work

No matter what value I set to "brighten" things up e.g. 0.1f to 1f or greater than 1f, it still stays the same shade of dark. I can confirm lights work great. Since there's no official DirectionalLight for top-down, adjusting ambient lighting is probably the next best thing.

If this is normal behavior, could it be amended so ambient lighting can be bright as day / dark as night?

Thanks.

Do the box2dlights 1.3 release

Hi there,

We are ready to release new version 1.3 of box2dlights.
As it's first time for me, could you please guide me if there are any changes that should be done for this before or after?

Thanks beforehand.

1.3 version

I use Gradle updata to 1.3 version that has some wrong with:

FAILURE: Build failed with an exception.

PointLight bleeding into blocked areas

I procedurally generate light blocking areas using static Box2D bodies, and I've come across an issue where point lights sometimes penetrate these bodies, depending on where the light source is.

Using the debug renderer The image below shows what I mean, the some of the green boxes to the left side of the character has light bleeding into them:
bleeding

I have worse pictures, where the light illuminates entire boxes of blocked areas. It seems to happen more with light shed toward the left, and seldom on areas to the right. Using cone lights, box2dLights works perfectly, no bleeding at all.

I've played around with softness, and the length of softness, but the issue still occurs.

Edit 1:
An idea hit me, so I increased the ray count, and it helped dramatically. I was using modest values of 5 to 20. I found that it had to be a value from around 50 to 100+, and I'm wondering if it really has to be like this, since it seems to be expensive if point lights have to have at least this much rays, in order to collide correctly with box2d bodies.

Calling RayHandler.updateAndRender() confuses ScreenUtils

I take screenshots as usual in libGDX via ScreenUtils.getFrameBufferPixmap(), which works fine. Hoever, when I call RayHandler.updateAndRender() during rendering, then the screenshot only contains those assets rendered after this call. All other pixels in the screenshot are transparent.

What is the best way to deal with this issue?

Missing 1.2 for gradle

The docs state to include

compile "com.badlogicgames.box2dlights:box2dlights:1.2"

however v1.2 is not yet available on Maven Central

Allow to set the length of shadows

Currently in box2dlights a box2d body either casts a shadow or not, there is no in-between. However, in my application I need to specify the length of the shadow for each object, depending on the objects height (in order to simulate a 3d effect).

For example, if the object that would cast the shadow is tall then the shadow is long. But if the object is small, not as tall as the light source height, then the shadow would be shorter.

Would it be hard to implement such a feature in box2dlights?

Generating shadow from 2d image

I wanted know if I can generate a shadow from a 2d image. For example: I have a coke cane and I want to generate a shadow such that it drops on the table or horizontal surface on right side of the coke. Then I want to create an image/bitmap of the coke & shadow combined. A little bit of hints will be very helpful.

Compatible with latest libgdx nightly?

I just updated my game from a very old box2dlights version and a very old libgdx version to the latest. Those were probably 2013 versions.
First I only updated box2Dlights, which worked fine; Then I updated libgdx and now I am getting

org.lwjgl.opengl.OpenGLException: Cannot use Buffers when Array Buffer Object is enabled
upon
at box2dLight.RayHandler.updateAndRender(RayHandler.java:263)

I could be doing something wrong but seeing as this code worked perfectly before, I am not sure. It would appear that a VBO is bound or not and conflicting... or something

RayHandler isn't working in 1.1

I'm getting an error when calling the render method of the rayHandler.
Error Message:
java.lang.NoSuchFieldError: gl at box2dLight.RayHandler.render(RayHandler.java:221)

Re-factor and prepeare box2lights tests for 1.3 release

  1. Re-factor test project so that it will include or switch between all following light types:
    1.1. PointLight
    1.2. ConeLight
    1.3. DirectionalLight
    1.4. ChainLight [new in 1.3]
  2. Add input-handled ability for run-time lights property changing (e.g. for distance and direction)
  3. Add input-handled example of run-time blending modes changing

Light has no getDirection

Either I am really dumb or there is no getDirection method anywhere. I have redownloaded the whole lib and searched through the code, it is nowhere to be found.

Light blinking

Hello, I have some problem. While camera is moving, the lights are blinking. The problem can be solved by increasing FBO size, but this way reduces FPS so much. You can see problem in this video: https://2ch.hk/gd/src/1406381150994.webm
How can i fix it?

Create method for adding light to RayHandler

Instead of inserting light after creating new instance, create a method to add light to RayHandler.
I think that the current behaviour is not much common, given that in various situations you want to create the light but not immediately start to use it, or even have created RayHandler instance yet.

Do the box2dlights 1.4 release

Hi Team,

Much time passed since 1.3 and we got some interesting changes (many thanks to piotr-j for custom light shader support). So could we, please, do the new 1.4 release and push it to maven?

Changes introduces since 1.3 (hope I not missed anything):

  • Added ability to resize the HayHandler's FBO
  • Added ability to set custom light shader for HayHandler
  • Added Light.setIgnoreAttachedBody(bool) to allow light ignore all the fixtures of body attached to
  • Added Light.getRayNum() method
  • Added Light.remove(bool) method with conditional disposing, so that light could be removed/added to rayHandler without re-creation
  • [API Change] Light.setContactFilter(...) is now not static and light specific, the static method for all lights is now called setGlobalContactFilter(...)
  • [API Change] Deprecated the RayHandler.setCombinedMatrix(Matrix4) due to the issues with it - use the setCombinedMatrix(OrthographicCamera) instead
  • Fixed issue of box2dlights rendering incompatibility with ScreenUtils.getFrameBufferPixmap on some devices (issue #43)

v1.2 - v1.3 light color differences

I am actually using box2dlights 1.2 with this settings :

// Initialize light ray handler
RayHandler.useDiffuseLight(true);
rayHandler = new RayHandler(world);
rayHandler.setAmbientLight(0.0f);

...
PointLight light = new PointLight(rayHandler, 32, Color.YELLOW, 30, 0, 0);
//light.setStaticLight(true);
light.setSoft(true);
light.attachToBody(body, 0, 0);

That render this :
https://i.imgur.com/rugDUNt.jpg

I have tried to upgrade to 1.3 but I got a strange behavior with same code :
https://i.imgur.com/po5rK3c.jpg
color is dull and light feel more darker.

Why ?

EDIT: I Saw that : rinold@e8c1010#diff-bb6de2497b7e4551aee180796561d089R541 but I cannot modify diffuse blend function from RayHandler (from master). How to make light more flashy ?

Ability to specify custom shaders

Currently, all shaders are hardcoded in the library. There is no way of altering them without running from the source. I propose adding a map with shader type and ShaderProgram to the RayHandler and setters so they can be changed during runtime. This is easy enough to implement. The main problem would be support for extra uniforms, as it would complicate the code a bit. Ill submit pull request with implementation sometime soonish.

My end goal is to update shaders to support some sort of normal maps. What do you think?

Create Spot light

Create a Spot light type, which could be just a point light with limited radius range and constant falloff.

LightDefs?

You know how Box2D has things like BodyDefs, FixtureDefs, and various flavors of JointDefs? Why not do a similar thing for the various subclasses of Light?

Box2dlights 1.3 , robovm 1.4.0 , libgdx 1.6.3 -> NoSuchMethodError

It seems 1.6.2 broke this

java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/Texture;
    at box2dLight.LightMap.gaussianBlur(LightMap.java:76)
    at box2dLight.LightMap.render(LightMap.java:37)
    at box2dLight.RayHandler.render(RayHandler.java:328)
    at box2dLight.RayHandler.updateAndRender(RayHandler.java:262)

Attached coneLight angle offset

Hello there,

Currently if you create a ConeLight you can set its world position, cone aperture and direction, and that is just fine. However, if you attach the light to a physical body, there doesn't seem to be a way of setting a rotation offset between the light and the body - the light always points to where the body points its 0 angle (If you rotate the body, the light becomes rotated but there doesn't seem to be a way of giving an initial offset to this angle); i.e. the angle initially set is just ignored. So I have a car with front and back lights (2D car seen from the top), and I can't find a way of pointing one light to the front and the other one to the back, having both lights attached to the car body. In addition, in newer versions of the Box2DLights library I had to change the Light.attachToBody(body, x, y) method to Light.attachToBody(body), with no information about the change (haven't found any, I mean) and it would be great if the Box2D debugger could show the lights origin because it's a little troublesome.

So, is this rotation offset achievable without having to manually update a detached light's position and rotation?

Error on remove light

In version 1.2, when I call the method remove of the light, the app crash by this error:

java.lang.IllegalArgumentException: buffer not allocated with newUnsafeByteBuffer or already disposed
at com.badlogic.gdx.utils.BufferUtils.disposeUnsafeByteBuffer(BufferUtils.java:507)
at com.badlogic.gdx.graphics.glutils.VertexArray.dispose(VertexArray.java:67)
at com.badlogic.gdx.graphics.Mesh.dispose(Mesh.java:551)
at box2dLight.Light.remove(Light.java:115)

What is the solution?
Thanks

Changing properties at runtime - possible?

Hi,

I'd like to first say that I'm loving the work done here. It's fantastic, even running smoothly on a low-end Android with ~700 PointLights (oops).
I've come into two issues, here, and I'm not sure if what I'm trying to do is simply not possible or I'm doing it wrong. The first is not being able to change properties/values at runtime. If I have a button to, per se, change the color or size of a light, nothing happens, even though via the render method I should be updating the lights each frame.
The second is referencing (in any way) any light outside of the render() or create() methods. I simply get a NullPointerException, which I don't quite understand, because these methods are being called by the player way after the lights have been initialized and are functional.
I don't feel like code is necessary, everything is pretty normal and basic and where it should be (as in your demo code). If you'd like it, I can, but it's not convenient at the time.
fadd3bce9e894211a94525bf42a0c61e
The lines in you light classes pretty much point to adding the light to the RayHandler, if I recall correctly.

Also, sorry if this is the wrong place to post this. I've yet to receive a response about anything related anywhere else.

Set Falloff of lights

it would be really great if one could set the falloff value of a light source. What I want to achieve is a very bright light, but with basically (very low) distance. Full brightness on one spot, no softness whatsoever. But only for some lights.

Would that be easy to implement?

FREQ - Light flicker

I was thinking that it would be possible to simulate flickering lights, particularly for flame-like lights if light offsets could have options to be tied to box2d horizontal gravity, or have this effect be done internally in box2dlights. I know it's quite possible to do the offset calculation outside of box2dlights, but it'd be convenient if it's built in, so that everything is neatly tied to one render step.

[Solved] Y-axis culling

As soon as light gets out of screen it is being culled, which results in terrible looking snapping. It doesn't happen on X axis though. On X axis light goes off the screen, you can still see it, on Y it automatically dissappears.

Tested it on 1.2 and 1.3

[Solved] Rendering Issue in Mac and Linux laptop but not Windows Desktop

First of all, box2dlights is really awesome. Second of all, I can't seem to figure out why the graphics of my lights is kind of messed up when running on Linux or Mac. I've attached an image of what it looks like. Can anyone help me resolve this issue, like is it something I'm dong wrong?

upwnbog

RFE: expose RayNum in Light

There is no way from outside to get the RayNum of a Light.
Meaning it would completely suffice to have a "int getRayNum()"

Why would you ever need this? I am placing lights with my map editor, in the map editor I want to keep track of how many rays a light has, disable it, make it editable. And for obvious reasons I dont want to save this number myself for each light when its already in there.

Convenience method to get a light source's area

Box2dlights does all the magic under hood, computing lit areas from light sources automatically, which make it really great.

There are some situations, where the area lit by the light source, is useful, especially if it is the computed end-result i.e. collision with blocking areas. I know that, recently, there were convenience methods added for checking for points within a lit / shadowed area, but having the actual area to work with opens up a lot of things.

Can this information be exposed for use?

FitViewport issue

Hello,

I have a problem with rendering my game with box2dlights and FitViewport option.

My project use gdxVersion = 1.5.3 and box2dlights:1.2 or 1.3.

I use macbook pro with Eclipse and test my game for Desktop.

I have a ortho camera and FitViewport:

my renderer create method:

...
camera = new OrthographicCamera(640, 320);
viewport = new FitViewport(640, 320, camera);
camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);
camera.update();
...

my renderer render method:

camera.update();
....
batch.setProjectionMatrix(camera.combined);
....
rayHandler.setCombinedMatrix(camera.combined);
rayHandler.updateAndRender();

my resize() method:

renderer.getViewport().update(width, height);

renderer.getCamera().position.set(
                renderer.getCamera().viewportWidth / 2,
                renderer.getCamera().viewportHeight / 2, 0);

stage.getViewport().update(width, height, false);

after changing window size without using box2dlights my screen looks like this:

http://i59.tinypic.com/w12wb5.png

after changing windows size with box2dlights my screen looks like this:

http://i59.tinypic.com/2qmof3r.png

So it's looks like adding box2dlights disable correct work of FitViewport or i have a bug in my code.

I have no idea what is wrong with my code :(

Light rayhandler sometimes null causing NullPointerException

Hello again,

I'm having some trouble handling lights creation / destruction on my game. On my game, I create and destroy lights quite frequently (the character shoots bullets with a small light attached). Sometimes, when calling Light.remove(), the system throws an unhandled NullPointerException, like the one below:

03-13 14:45:47.294: E/AndroidRuntime(7099): FATAL EXCEPTION: GLThread 88127
03-13 14:45:47.294: E/AndroidRuntime(7099): Process: package.android, PID: 7099
03-13 14:45:47.294: E/AndroidRuntime(7099): java.lang.NullPointerException: Attempt to read from field 'com.badlogic.gdx.utils.Array box2dLight.RayHandler.lightList' on a null object reference
03-13 14:45:47.294: E/AndroidRuntime(7099):     at box2dLight.Light.remove(Light.java:212)
03-13 14:45:47.294: E/AndroidRuntime(7099):     at package.Globals.removePendingLights(Globals.java:144)
03-13 14:45:47.294: E/AndroidRuntime(7099):     at package.screens.TestScreen.render(TestScreen.java:78)
03-13 14:45:47.294: E/AndroidRuntime(7099):     at com.badlogic.gdx.Game.render(Game.java:46)
03-13 14:45:47.294: E/AndroidRuntime(7099):     at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:422)
03-13 14:45:47.294: E/AndroidRuntime(7099):     at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1531)
03-13 14:45:47.294: E/AndroidRuntime(7099):     at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1248)
03-13 14:45:51.344: E/AndroidGraphics(7099): waiting for pause synchronization took too long; assuming deadlock and killing
03-13 14:45:51.344: I/Process(7099): Sending signal. PID: 7099 SIG: 9

The way I'm handling lights removal is the same as bodies removal; in the main loop:

@Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        tweenManager.update(delta);

        worldStep(delta);
        player.removePendingBodies();
        player.getWeapon().removePendingBullets();
        Globals.removePendingLights();
       (...)
   }

The bad thing is this only happens sometimes, quite randomly (I haven't found any crash pattern yet). Any idea why this could be happening?

setIgnoreAttachedBody() not working

I have been trying to use the new setIgnoreAttachedBody() in the 1.4 snapshot and unfortunately it is not working.

light.attachToBody(ground);
light.setIgnoreAttachedBody(true);
System.out.println(light.getIgnoreAttachedBody());

This is returning false and shadows are still being cast on the ground body. I have tried putting setIgnoreAttachedBody() before attachToBody() as well. It appears it will work with a ConeLight but not a DirectionalLight.

Latest box2dlights version not in Maven

After you have kindly fixed the ScreenUtils bug I would like to use the new box2dlights version. However, it seems the latest version 1.4 is not in Maven, so I cannot use it in my Gradle build. The snapshot of 1.4 however does already contain the latest update:

http://libgdx.badlogicgames.com/box2dlights/

Are there any plans to release latest version 1.4 to Maven central anytime soon?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.