com.badlogic.gdx.utils.Bits Java Examples

The following examples show how to use com.badlogic.gdx.utils.Bits. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
/**
 * Get the triangle which this ray intersects. Returns null if no triangle is intersected.
 *
 * @param ray
 * @param distance
 * @param allowedMeshParts
 * @return
 */
public Triangle rayTest(Ray ray, float distance, Bits allowedMeshParts) {
	Triangle hitTriangle = null;

	tmpRayTestRayFrom.set(ray.origin);
	tmpRayTestRayTo.set(ray.direction).scl(distance).add(tmpRayTestRayFrom);
	raycastCallback.setHitFraction(1);
	raycastCallback.clearReport();
	raycastCallback.setFrom(tmpRayTestRayFrom);
	raycastCallback.setTo(tmpRayTestRayTo);
	raycastCallback.setAllowedMeshPartIndices(allowedMeshParts);
	collisionShape.performRaycast(raycastCallback, tmpRayTestRayFrom, tmpRayTestRayTo);

	if (raycastCallback.triangleIndex != -1) {
		hitTriangle = graph.getTriangleFromMeshPart(raycastCallback.partId, raycastCallback.triangleIndex);
	}
	return hitTriangle;
}
 
Example #2
Source File: FamilyManager.java    From ashley with Apache License 2.0 6 votes vote down vote up
private ImmutableArray<Entity> registerFamily(Family family) {
	ImmutableArray<Entity> entitiesInFamily = immutableFamilies.get(family);

	if (entitiesInFamily == null) {
		Array<Entity> familyEntities = new Array<Entity>(false, 16);
		entitiesInFamily = new ImmutableArray<Entity>(familyEntities);
		families.put(family, familyEntities);
		immutableFamilies.put(family, entitiesInFamily);
		entityListenerMasks.put(family, new Bits());

		for (Entity entity : entities){
			updateFamilyMembership(entity);
		}
	}

	return entitiesInFamily;
}
 
Example #3
Source File: FamilyManager.java    From ashley with Apache License 2.0 6 votes vote down vote up
public void removeEntityListener (EntityListener listener) {
	for (int i = 0; i < entityListeners.size; i++) {
		EntityListenerData entityListenerData = entityListeners.get(i);
		if (entityListenerData.listener == listener) {
			// Shift down bitmasks by one step
			for (Bits mask : entityListenerMasks.values()) {
				for (int k = i, n = mask.length(); k < n; k++) {
					if (mask.get(k + 1)) {
						mask.set(k);
					} else {
						mask.clear(k);
					}
				}
			}

			entityListeners.removeIndex(i--);
		}
	}
}
 
Example #4
Source File: GameEngine.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
public Entity rayTest(Ray ray, Vector3 hitPointWorld, short belongsToFlag, short collidesWithFlag,
					  float rayDistance, Bits layers) {
	rayFrom.set(ray.origin);
	rayTo.set(ray.direction).scl(rayDistance).add(rayFrom);
	callback.setCollisionObject(null);
	callback.setClosestHitFraction(1f);
	callback.setRay(ray, rayDistance);
	callback.setLayers(layers);

	callback.setCollisionFilterMask(belongsToFlag);
	callback.setCollisionFilterGroup(collidesWithFlag);

	dynamicsWorld.rayTest(rayFrom, rayTo, callback);

	if (callback.hasHit()) {
		if (hitPointWorld != null) {
			callback.getHitPointWorld(hitPointWorld);
		}
		long entityId = callback.getCollisionObject().getUserPointer();
		return getEntity(entityId);
	}
	return null;
}
 
Example #5
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 6 votes vote down vote up
/**
 * Make a ray test at this point, using a ray spanning from far up in the sky, to far down in the ground,
 * along the up axis.
 *
 * @param testPoint        The test point
 * @param out              The point of intersection between ray and triangle
 * @param allowedMeshParts Which mesh parts to test. Null if all meshparts should be tested.
 * @return The triangle, or null if ray did not hit any triangles.
 */
public Triangle verticalRayTest(Vector3 testPoint, Vector3 out, Bits allowedMeshParts) {
	tmpRayVerticalRayTest.set(
			tmpVerticalRayTest1.set(Constants.V3_UP).scl(500).add(testPoint),
			tmpVerticalRayTest2.set(Constants.V3_DOWN));
	Triangle hitTri = rayTest(tmpRayVerticalRayTest, 1000, allowedMeshParts);
	if (hitTri == null) {
		// TODO: Perhaps this should be Nan?
		out.set(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
		return null;
	} else {

		Intersector.intersectRayTriangle(tmpRayVerticalRayTest, hitTri.a, hitTri.b, hitTri.c, out);
		return hitTri;
	}
}
 
Example #6
Source File: Family.java    From ashley with Apache License 2.0 6 votes vote down vote up
/** @return Whether the entity matches the family requirements or not */
public boolean matches (Entity entity) {
	Bits entityComponentBits = entity.getComponentBits();

	if (!entityComponentBits.containsAll(all)) {
		return false;
	}

	if (!one.isEmpty() && !one.intersects(entityComponentBits)) {
		return false;
	}

	if (!exclude.isEmpty() && exclude.intersects(entityComponentBits)) {
		return false;
	}

	return true;
}
 
Example #7
Source File: Family.java    From ashley with Apache License 2.0 5 votes vote down vote up
private static String getFamilyHash (Bits all, Bits one, Bits exclude) {
	StringBuilder stringBuilder = new StringBuilder();
	if (!all.isEmpty()) {
		stringBuilder.append("{all:").append(getBitsString(all)).append("}");
	}
	if (!one.isEmpty()) {
		stringBuilder.append("{one:").append(getBitsString(one)).append("}");
	}
	if (!exclude.isEmpty()) {
		stringBuilder.append("{exclude:").append(getBitsString(exclude)).append("}");
	}
	return stringBuilder.toString();
}
 
Example #8
Source File: NavMeshGraph.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
/**
 * Get an array of the vertex indices from the mesh. Any vertices which share the same position will be counted
 * as a single vertex and share the same index. That is, position duplicates will be filtered out.
 *
 * @param mesh
 * @return
 */
private static short[] getUniquePositionVertexIndices(Mesh mesh) {
	FloatBuffer verticesBuffer = mesh.getVerticesBuffer();
	int positionOffset = mesh.getVertexAttributes().findByUsage(VertexAttributes.Usage.Position).offset / 4;
	// Number of array elements which make up a vertex
	int vertexSize = mesh.getVertexSize() / 4;
	// The indices tell us which vertices are part of a triangle.
	short[] indices = new short[mesh.getNumIndices()];
	mesh.getIndices(indices);
	// Marks true if an index has already been compared to avoid unnecessary comparisons
	Bits handledIndices = new Bits(mesh.getNumIndices());

	for (int i = 0; i < indices.length; i++) {
		short indexI = indices[i];
		if (handledIndices.get(indexI)) {
			// Index handled in an earlier iteration
			continue;
		}
		int vBufIndexI = indexI * vertexSize + positionOffset;
		float xi = verticesBuffer.get(vBufIndexI++);
		float yi = verticesBuffer.get(vBufIndexI++);
		float zi = verticesBuffer.get(vBufIndexI++);
		for (int j = i + 1; j < indices.length; j++) {
			short indexJ = indices[j];
			int vBufIndexJ = indexJ * vertexSize + positionOffset;
			float xj = verticesBuffer.get(vBufIndexJ++);
			float yj = verticesBuffer.get(vBufIndexJ++);
			float zj = verticesBuffer.get(vBufIndexJ++);
			if (xi == xj && yi == yj && zi == zj) {
				indices[j] = indexI;
			}
		}
		handledIndices.set(indexI);
	}
	return indices;
}
 
Example #9
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate a triangle graph path between two triangles which are intersected by the rays.
 *
 * @param fromRay
 * @param toRay
 * @param allowedMeshParts
 * @param distance
 * @param path
 * @return
 */
public boolean getPath(Ray fromRay, Ray toRay, Bits allowedMeshParts,
					   float distance, NavMeshGraphPath path) {

	Triangle fromTri = rayTest(fromRay, distance, allowedMeshParts);
	if (fromTri == null) {
		Gdx.app.debug(TAG, "From triangle not found.");
		return false;
	}
	Vector3 fromPoint = new Vector3();
	Intersector.intersectRayTriangle(fromRay, fromTri.a, fromTri.b, fromTri.c, fromPoint);

	return getPath(fromTri, fromPoint, toRay, allowedMeshParts, distance, path);
}
 
Example #10
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
/**
 * Get a random triangle on the navigation mesh, on any of the allowed mesh parts.
 * The probability distribution is even in world space, as opposed to triangle index,
 * meaning large triangles will be chosen more often than small ones.
 * <p/>
 * Example usage, to get a random point on the second navigation mesh part:
 * allowedMeshParts.clear();
 * allowedMeshParts.set(1);
 * Triangle randomTri = navmesh.getRandomTriangle(allowedMeshParts);
 * Vector3 randomPoint = new Vector3();
 * randomTri.getRandomPoint(randomPoint);
 *
 * @param allowedMeshParts Bits representing allowed mesh part indices.
 * @return A random triangle.
 */
public Triangle getRandomTriangle(Bits allowedMeshParts) {
	tmpFloatArrayGetRandomTriangle.clear();
	tmpFloatArrayGetRandomTriangle.ordered = true;
	tmpTriArrayGetRandomTriangle.clear();
	tmpTriArrayGetRandomTriangle.ordered = true;

	// To get a uniform distribution over the triangles in the mesh parts
	// we must take areas of the triangles into account.
	for (int mpIndex = 0; mpIndex < graph.getMeshPartCount(); mpIndex++) {
		if (allowedMeshParts.get(mpIndex)) {
			for (int triIndex = 0; triIndex < graph.getTriangleCount(mpIndex); triIndex++) {
				Triangle tri = graph.getTriangleFromMeshPart(mpIndex, triIndex);
				float integratedArea = 0;
				if (tmpFloatArrayGetRandomTriangle.size > 0) {
					integratedArea = tmpFloatArrayGetRandomTriangle.get(tmpFloatArrayGetRandomTriangle.size - 1);
				}
				tmpFloatArrayGetRandomTriangle.add(integratedArea + tri.area());
				tmpTriArrayGetRandomTriangle.add(tri);
			}
		}
	}
	if (tmpFloatArrayGetRandomTriangle.size == 0) {
		return null;
	}
	float r = MathUtils.random(0f, tmpFloatArrayGetRandomTriangle.get(tmpFloatArrayGetRandomTriangle.size - 1));
	int i;
	for (i = 0; i < tmpFloatArrayGetRandomTriangle.size; i++) {
		if (r <= tmpFloatArrayGetRandomTriangle.get(i)) {
			break;
		}
	}
	return tmpTriArrayGetRandomTriangle.get(i);
}
 
Example #11
Source File: ComponentType.java    From ashley with Apache License 2.0 5 votes vote down vote up
/**
 * @param componentTypes list of {@link Component} classes
 * @return Bits representing the collection of components for quick comparison and matching. See
 *         {@link Family#getFor(Bits, Bits, Bits)}.
 */
public static Bits getBitsFor (Class<? extends Component>... componentTypes) {
	Bits bits = new Bits();

	int typesLength = componentTypes.length;
	for (int i = 0; i < typesLength; i++) {
		bits.set(ComponentType.getIndexFor(componentTypes[i]));
	}

	return bits;
}
 
Example #12
Source File: Family.java    From ashley with Apache License 2.0 5 votes vote down vote up
/** Private constructor, use static method Family.getFamilyFor() */
private Family (Bits all, Bits any, Bits exclude) {
	this.all = all;
	this.one = any;
	this.exclude = exclude;
	this.index = familyIndex++;
}
 
Example #13
Source File: NavMesh.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate a triangle graph path from a start triangle to the triangle which is intersected by a ray.
 *
 * @param fromTri
 * @param fromPoint
 * @param toRay
 * @param allowedMeshParts
 * @param distance
 * @param path
 * @return
 */
public boolean getPath(Triangle fromTri, Vector3 fromPoint, Ray toRay, Bits allowedMeshParts,
					   float distance, NavMeshGraphPath path) {
	Triangle toTri = rayTest(toRay, distance, allowedMeshParts);
	if (toTri == null) {
		Gdx.app.debug(TAG, "To triangle not found.");
		return false;
	}
	Vector3 toPoint = new Vector3();
	Intersector.intersectRayTriangle(toRay, toTri.a, toTri.b, toTri.c, toPoint);

	return getPath(fromTri, fromPoint, toTri, toPoint, path);
}
 
Example #14
Source File: Family.java    From ashley with Apache License 2.0 5 votes vote down vote up
private static String getBitsString (Bits bits) {
	StringBuilder stringBuilder = new StringBuilder();

	int numBits = bits.length();
	for (int i = 0; i < numBits; ++i) {
		stringBuilder.append(bits.get(i) ? "1" : "0");
	}

	return stringBuilder.toString();
}
 
Example #15
Source File: Entity.java    From ashley with Apache License 2.0 5 votes vote down vote up
/** Creates an empty Entity. */
public Entity () {
	components = new Bag<Component>();
	componentsArray = new Array<Component>(false, 16);
	immutableComponentsArray = new ImmutableArray<Component>(componentsArray);
	componentBits = new Bits();
	familyBits = new Bits();
	flags = 0;

	componentAdded = new Signal<Entity>();
	componentRemoved = new Signal<Entity>();
}
 
Example #16
Source File: FamilyManager.java    From ashley with Apache License 2.0 5 votes vote down vote up
public void addEntityListener (Family family, int priority, EntityListener listener) {
	registerFamily(family);

	int insertionIndex = 0;
	while (insertionIndex < entityListeners.size) {
		if (entityListeners.get(insertionIndex).priority <= priority) {
			insertionIndex++;
		} else {
			break;
		}
	}

	// Shift up bitmasks by one step
	for (Bits mask : entityListenerMasks.values()) {
		for (int k = mask.length(); k > insertionIndex; k--) {
			if (mask.get(k - 1)) {
				mask.set(k);
			} else {
				mask.clear(k);
			}
		}
		mask.clear(insertionIndex);
	}

	entityListenerMasks.get(family).set(insertionIndex);

	EntityListenerData entityListenerData = new EntityListenerData();
	entityListenerData.listener = listener;
	entityListenerData.priority = priority;
	entityListeners.insert(insertionIndex, entityListenerData);
}
 
Example #17
Source File: EntityTests.java    From ashley with Apache License 2.0 5 votes vote down vote up
@Test
public void addAndRemoveComponent () {
	Entity entity = new Entity();

	entity.add(new ComponentA());

	assertEquals(1, entity.getComponents().size());

	Bits componentBits = entity.getComponentBits();
	int componentAIndex = ComponentType.getIndexFor(ComponentA.class);

	for (int i = 0; i < componentBits.length(); ++i) {
		assertEquals(i == componentAIndex, componentBits.get(i));
	}

	assertNotNull(am.get(entity));
	assertNull(bm.get(entity));
	assertTrue(am.has(entity));
	assertFalse(bm.has(entity));

	entity.remove(ComponentA.class);

	assertEquals(0, entity.getComponents().size());

	for (int i = 0; i < componentBits.length(); ++i) {
		assertFalse(componentBits.get(i));
	}

	assertNull(am.get(entity));
	assertNull(bm.get(entity));
	assertFalse(am.has(entity));
	assertFalse(bm.has(entity));
}
 
Example #18
Source File: EntityTests.java    From ashley with Apache License 2.0 5 votes vote down vote up
@Test
public void addAndRemoveAllComponents () {
	Entity entity = new Entity();

	entity.add(new ComponentA());
	entity.add(new ComponentB());

	assertEquals(2, entity.getComponents().size());

	Bits componentBits = entity.getComponentBits();
	int componentAIndex = ComponentType.getIndexFor(ComponentA.class);
	int componentBIndex = ComponentType.getIndexFor(ComponentB.class);

	for (int i = 0; i < componentBits.length(); ++i) {
		assertEquals(i == componentAIndex || i == componentBIndex, componentBits.get(i));
	}

	assertNotNull(am.get(entity));
	assertNotNull(bm.get(entity));
	assertTrue(am.has(entity));
	assertTrue(bm.has(entity));

	entity.removeAll();

	assertEquals(0, entity.getComponents().size());

	for (int i = 0; i < componentBits.length(); ++i) {
		assertFalse(componentBits.get(i));
	}

	assertNull(am.get(entity));
	assertNull(bm.get(entity));
	assertFalse(am.has(entity));
	assertFalse(bm.has(entity));
}
 
Example #19
Source File: Map.java    From riiablo with Apache License 2.0 5 votes vote down vote up
/**
 * @param x   world sub-tile
 * @param y   world sub-tile
 * @param tx  world tile
 * @param ty  world tile
 * @param stx sub-tile (0-4)
 * @param sty sub-tile (0-4)
 */
// TODO: x,y alone should be enough, but others are available in MapRenderer on each position change anyways
public void updatePopPads(Bits bits, int x, int y, int tx, int ty, int stx, int sty) {
  bits.clear();
  Zone zone = getZone(x, y);
  if (zone != null) {
    Map.Preset preset = zone.getGrid(tx, ty);
    if (preset != null) {
      int presetX = zone.getGridX(tx) + stx;
      int presetY = zone.getGridX(ty) + sty;
      preset.updatePopPads(bits, presetX, presetY);
    }
  }
}
 
Example #20
Source File: Map.java    From riiablo with Apache License 2.0 5 votes vote down vote up
void updatePopPads(Bits bits, int x, int y) {
  if (popPads == null) return;
  for (PopPad popPad : popPads.values()) {
    if (popPad.contains(x, y)) {
      bits.set(DT1.Tile.Index.subIndex(popPad.id));
    }
  }
}
 
Example #21
Source File: Animation.java    From riiablo with Apache License 2.0 5 votes vote down vote up
protected Layer loadAll(Bits dirs) {
  for (int d = dirs.nextSetBit(0); d >= 0; d = dirs.nextSetBit(d + 1)) {
    load(d);
  }

  return this;
}
 
Example #22
Source File: FollowPathSteerer.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
public boolean calculateNewPath(Ray ray, Bits visibleLayers) {
	if (GameScreen.screen.engine.getScene().navMesh.getPath(
			steerableBody.getCurrentTriangle(),
			steerableBody.getGroundPosition(tmpVec1),
			ray, visibleLayers,
			GameSettings.CAMERA_PICK_RAY_DST,
			navMeshGraphPath)) {

		calculateNewPath0();
		return true;
	}
	return false;
}
 
Example #23
Source File: NavMeshDebugDrawer.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
public void drawNavMesh(MyShapeRenderer shapeRenderer,
						SpriteBatch spriteBatch,
						NavMesh navMesh,
						GameCharacter character,
						Bits visibleLayers,
						Camera camera,
						BitmapFont font) {

	this.visibleLayers = visibleLayers;
	this.shapeRenderer = shapeRenderer;
	this.navMesh = navMesh;

	if (shapeRenderer.isDrawing()) {
		shapeRenderer.end();
	}

	Gdx.gl.glEnable(GL20.GL_BLEND);
	Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
	shapeRenderer.begin(MyShapeRenderer.ShapeType.Line);
	drawNavMeshTriangles();
	if (character != null && character.steerer instanceof FollowPathSteerer) {
		FollowPathSteerer fpSteerer = (FollowPathSteerer)character.steerer;
		drawPathTriangles(fpSteerer.navMeshGraphPath, character.getCurrentTriangle());
		if (fpSteerer.navMeshPointPath.getSize() > 0) {
			drawPathPoints(fpSteerer.navMeshPointPath);
		}
		drawClosestPointDebug(character);
	}
	shapeRenderer.end();
	Gdx.gl.glDisable(GL20.GL_BLEND);

	drawNavMeshIndices(spriteBatch, camera, font);
}
 
Example #24
Source File: HumanCharacter.java    From GdxDemo3D with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMovementRequest(Ray ray, Bits visibleLayers) {
	// A man only moves if is idle or already moving
	// For instance, the movement request will be ignored if the man is throwing the stick
	HumanState state = stateMachine.getCurrentState();
	if (state.isIdleState() || state.isMovementState()) {
		followPathSteerer.calculateNewPath(ray, visibleLayers);
	}
}
 
Example #25
Source File: GameStage.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
public void setVisibleLayers(Bits visibleLayers) {
	this.visibleLayers.clear();
	this.visibleLayers.or(visibleLayers);
	layerController.setLayer(visibleLayers.nextClearBit(0) - 1);
	notifyObserversLayerChanged(this.visibleLayers);
}
 
Example #26
Source File: FamilyManager.java    From ashley with Apache License 2.0 4 votes vote down vote up
@Override
protected Bits newObject () {
	return new Bits();
}
 
Example #27
Source File: FamilyManager.java    From ashley with Apache License 2.0 4 votes vote down vote up
public void updateFamilyMembership (Entity entity) {
	// Find families that the entity was added to/removed from, and fill
	// the bitmasks with corresponding listener bits.
	Bits addListenerBits = bitsPool.obtain();
	Bits removeListenerBits = bitsPool.obtain();

	for (Family family : entityListenerMasks.keys()) {
		final int familyIndex = family.getIndex();
		final Bits entityFamilyBits = entity.getFamilyBits();

		boolean belongsToFamily = entityFamilyBits.get(familyIndex);
		boolean matches = family.matches(entity) && !entity.removing;

		if (belongsToFamily != matches) {
			final Bits listenersMask = entityListenerMasks.get(family);
			final Array<Entity> familyEntities = families.get(family);
			if (matches) {
				addListenerBits.or(listenersMask);
				familyEntities.add(entity);
				entityFamilyBits.set(familyIndex);
			} else {
				removeListenerBits.or(listenersMask);
				familyEntities.removeValue(entity, true);
				entityFamilyBits.clear(familyIndex);
			}
		}
	}

	// Notify listeners; set bits match indices of listeners
	notifying = true;
	Object[] items = entityListeners.begin();

	try {
		for (int i = removeListenerBits.nextSetBit(0); i >= 0; i = removeListenerBits.nextSetBit(i + 1)) {
			((EntityListenerData)items[i]).listener.entityRemoved(entity);
		}

		for (int i = addListenerBits.nextSetBit(0); i >= 0; i = addListenerBits.nextSetBit(i + 1)) {
			((EntityListenerData)items[i]).listener.entityAdded(entity);
		}
	}
	finally {
		addListenerBits.clear();
		removeListenerBits.clear();
		bitsPool.free(addListenerBits);
		bitsPool.free(removeListenerBits);
		entityListeners.end();
		notifying = false;	
	}
}
 
Example #28
Source File: GameEngine.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
public void setLayers(Bits layers) {
	this.layers = layers;
}
 
Example #29
Source File: GameEngine.java    From GdxDemo3D with Apache License 2.0 4 votes vote down vote up
public Bits getVisibleLayers() {
	return visibleLayers;
}
 
Example #30
Source File: Entity.java    From ashley with Apache License 2.0 4 votes vote down vote up
/** @return This Entity's {@link Family} bits, describing all the {@link EntitySystem}s it currently is being processed by. */
Bits getFamilyBits () {
	return familyBits;
}