blob: f10666749981b087146419952aebd4a84b076d7d [file] [log] [blame]
Romain Guy3b748a42013-04-17 18:54:38 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.content.Context;
20import android.content.pm.PackageInfo;
21import android.content.pm.PackageManager;
22import android.content.res.Resources;
23import android.graphics.Atlas;
24import android.graphics.Bitmap;
25import android.graphics.Canvas;
26import android.graphics.Paint;
27import android.graphics.PixelFormat;
28import android.graphics.PorterDuff;
29import android.graphics.PorterDuffXfermode;
30import android.graphics.drawable.Drawable;
31import android.os.Environment;
32import android.os.RemoteException;
33import android.os.SystemProperties;
34import android.util.Log;
35import android.util.LongSparseArray;
36import android.view.GraphicBuffer;
37import android.view.IAssetAtlas;
38
39import java.io.BufferedReader;
40import java.io.BufferedWriter;
41import java.io.File;
42import java.io.FileInputStream;
43import java.io.FileNotFoundException;
44import java.io.FileOutputStream;
45import java.io.IOException;
46import java.io.InputStreamReader;
47import java.io.OutputStreamWriter;
48import java.util.ArrayList;
John Reckdad7d84c2014-12-09 12:33:26 -080049import java.util.Collection;
Romain Guy3b748a42013-04-17 18:54:38 -070050import java.util.Collections;
51import java.util.Comparator;
John Reckdad7d84c2014-12-09 12:33:26 -080052import java.util.HashSet;
Romain Guy3b748a42013-04-17 18:54:38 -070053import java.util.List;
54import java.util.concurrent.CountDownLatch;
55import java.util.concurrent.TimeUnit;
56import java.util.concurrent.atomic.AtomicBoolean;
57
58/**
59 * This service is responsible for packing preloaded bitmaps into a single
60 * atlas texture. The resulting texture can be shared across processes to
61 * reduce overall memory usage.
62 *
63 * @hide
64 */
65public class AssetAtlasService extends IAssetAtlas.Stub {
66 /**
67 * Name of the <code>AssetAtlasService</code>.
68 */
69 public static final String ASSET_ATLAS_SERVICE = "assetatlas";
70
John Reckdad7d84c2014-12-09 12:33:26 -080071 private static final String LOG_TAG = "AssetAtlas";
Romain Guy3b748a42013-04-17 18:54:38 -070072
73 // Turns debug logs on/off. Debug logs are kept to a minimum and should
74 // remain on to diagnose issues
75 private static final boolean DEBUG_ATLAS = true;
76
77 // When set to true the content of the atlas will be saved to disk
78 // in /data/system/atlas.png. The shared GraphicBuffer may be empty
79 private static final boolean DEBUG_ATLAS_TEXTURE = false;
80
81 // Minimum size in pixels to consider for the resulting texture
82 private static final int MIN_SIZE = 768;
83 // Maximum size in pixels to consider for the resulting texture
84 private static final int MAX_SIZE = 2048;
85 // Increment in number of pixels between size variants when looking
86 // for the best texture dimensions
87 private static final int STEP = 64;
88
89 // This percentage of the total number of pixels represents the minimum
90 // number of pixels we want to be able to pack in the atlas
91 private static final float PACKING_THRESHOLD = 0.8f;
92
93 // Defines the number of int fields used to represent a single entry
94 // in the atlas map. This number defines the size of the array returned
95 // by the getMap(). See the mAtlasMap field for more information
96 private static final int ATLAS_MAP_ENTRY_FIELD_COUNT = 4;
97
98 // Specifies how our GraphicBuffer will be used. To get proper swizzling
99 // the buffer will be written to using OpenGL (from JNI) so we can leave
100 // the software flag set to "never"
101 private static final int GRAPHIC_BUFFER_USAGE = GraphicBuffer.USAGE_SW_READ_NEVER |
102 GraphicBuffer.USAGE_SW_WRITE_NEVER | GraphicBuffer.USAGE_HW_TEXTURE;
103
104 // This boolean is set to true if an atlas was successfully
105 // computed and rendered
106 private final AtomicBoolean mAtlasReady = new AtomicBoolean(false);
107
108 private final Context mContext;
109
110 // Version name of the current build, used to identify changes to assets list
111 private final String mVersionName;
112
113 // Holds the atlas' data. This buffer can be mapped to
114 // OpenGL using an EGLImage
115 private GraphicBuffer mBuffer;
116
117 // Describes how bitmaps are placed in the atlas. Each bitmap is
118 // represented by several entries in the array:
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000119 // long0: SkBitmap*, the native bitmap object
120 // long1: x position
121 // long2: y position
122 // long3: rotated, 1 if the bitmap must be rotated, 0 otherwise
123 private long[] mAtlasMap;
Romain Guy3b748a42013-04-17 18:54:38 -0700124
125 /**
126 * Creates a new service. Upon creating, the service will gather the list of
127 * assets to consider for packing into the atlas and spawn a new thread to
128 * start the packing work.
129 *
130 * @param context The context giving access to preloaded resources
131 */
132 public AssetAtlasService(Context context) {
133 mContext = context;
134 mVersionName = queryVersionName(context);
135
John Reckdad7d84c2014-12-09 12:33:26 -0800136 Collection<Bitmap> bitmaps = new HashSet<Bitmap>(300);
Romain Guy3b748a42013-04-17 18:54:38 -0700137 int totalPixelCount = 0;
138
139 // We only care about drawables that hold bitmaps
140 final Resources resources = context.getResources();
141 final LongSparseArray<Drawable.ConstantState> drawables = resources.getPreloadedDrawables();
142
143 final int count = drawables.size();
144 for (int i = 0; i < count; i++) {
John Reckdad7d84c2014-12-09 12:33:26 -0800145 try {
146 totalPixelCount += drawables.valueAt(i).addAtlasableBitmaps(bitmaps);
147 } catch (Throwable t) {
148 Log.e("AssetAtlas", "Failed to fetch preloaded drawable state", t);
149 throw t;
Romain Guy3b748a42013-04-17 18:54:38 -0700150 }
151 }
152
John Reckdad7d84c2014-12-09 12:33:26 -0800153 ArrayList<Bitmap> sortedBitmaps = new ArrayList<Bitmap>(bitmaps);
Romain Guy3b748a42013-04-17 18:54:38 -0700154 // Our algorithms perform better when the bitmaps are first sorted
155 // The comparator will sort the bitmap by width first, then by height
John Reckdad7d84c2014-12-09 12:33:26 -0800156 Collections.sort(sortedBitmaps, new Comparator<Bitmap>() {
Romain Guy3b748a42013-04-17 18:54:38 -0700157 @Override
158 public int compare(Bitmap b1, Bitmap b2) {
159 if (b1.getWidth() == b2.getWidth()) {
160 return b2.getHeight() - b1.getHeight();
161 }
162 return b2.getWidth() - b1.getWidth();
163 }
164 });
165
166 // Kick off the packing work on a worker thread
John Reckdad7d84c2014-12-09 12:33:26 -0800167 new Thread(new Renderer(sortedBitmaps, totalPixelCount)).start();
Romain Guy3b748a42013-04-17 18:54:38 -0700168 }
169
170 /**
171 * Queries the version name stored in framework's AndroidManifest.
172 * The version name can be used to identify possible changes to
173 * framework resources.
174 *
175 * @see #getBuildIdentifier(String)
176 */
177 private static String queryVersionName(Context context) {
178 try {
179 String packageName = context.getPackageName();
180 PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
181 return info.versionName;
182 } catch (PackageManager.NameNotFoundException e) {
183 Log.w(LOG_TAG, "Could not get package info", e);
184 }
185 return null;
186 }
187
188 /**
189 * Callback invoked by the server thread to indicate we can now run
190 * 3rd party code.
191 */
Svetoslav Ganova0027152013-06-25 14:59:53 -0700192 public void systemRunning() {
Romain Guy3b748a42013-04-17 18:54:38 -0700193 }
194
195 /**
196 * The renderer does all the work:
197 */
198 private class Renderer implements Runnable {
199 private final ArrayList<Bitmap> mBitmaps;
200 private final int mPixelCount;
201
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000202 private long mNativeBitmap;
Romain Guy3b748a42013-04-17 18:54:38 -0700203
204 // Used for debugging only
205 private Bitmap mAtlasBitmap;
206
207 Renderer(ArrayList<Bitmap> bitmaps, int pixelCount) {
208 mBitmaps = bitmaps;
209 mPixelCount = pixelCount;
210 }
211
212 /**
213 * 1. On first boot or after every update, brute-force through all the
214 * possible atlas configurations and look for the best one (maximimize
215 * number of packed assets and minimize texture size)
216 * a. If a best configuration was computed, write it out to disk for
217 * future use
218 * 2. Read best configuration from disk
219 * 3. Compute the packing using the best configuration
220 * 4. Allocate a GraphicBuffer
221 * 5. Render assets in the buffer
222 */
223 @Override
224 public void run() {
225 Configuration config = chooseConfiguration(mBitmaps, mPixelCount, mVersionName);
226 if (DEBUG_ATLAS) Log.d(LOG_TAG, "Loaded configuration: " + config);
227
228 if (config != null) {
229 mBuffer = GraphicBuffer.create(config.width, config.height,
230 PixelFormat.RGBA_8888, GRAPHIC_BUFFER_USAGE);
231
232 if (mBuffer != null) {
233 Atlas atlas = new Atlas(config.type, config.width, config.height, config.flags);
234 if (renderAtlas(mBuffer, atlas, config.count)) {
235 mAtlasReady.set(true);
236 }
237 }
238 }
239 }
240
241 /**
242 * Renders a list of bitmaps into the atlas. The position of each bitmap
243 * was decided by the packing algorithm and will be honored by this
244 * method. If need be this method will also rotate bitmaps.
245 *
246 * @param buffer The buffer to render the atlas entries into
247 * @param atlas The atlas to pack the bitmaps into
248 * @param packCount The number of bitmaps that will be packed in the atlas
249 *
250 * @return true if the atlas was rendered, false otherwise
251 */
252 @SuppressWarnings("MismatchedReadAndWriteOfArray")
253 private boolean renderAtlas(GraphicBuffer buffer, Atlas atlas, int packCount) {
254 // Use a Source blend mode to improve performance, the target bitmap
255 // will be zero'd out so there's no need to waste time applying blending
256 final Paint paint = new Paint();
257 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
258
259 // We always render the atlas into a bitmap. This bitmap is then
260 // uploaded into the GraphicBuffer using OpenGL to swizzle the content
261 final Canvas canvas = acquireCanvas(buffer.getWidth(), buffer.getHeight());
262 if (canvas == null) return false;
263
264 final Atlas.Entry entry = new Atlas.Entry();
265
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000266 mAtlasMap = new long[packCount * ATLAS_MAP_ENTRY_FIELD_COUNT];
267 long[] atlasMap = mAtlasMap;
Romain Guy3b748a42013-04-17 18:54:38 -0700268 int mapIndex = 0;
269
270 boolean result = false;
271 try {
272 final long startRender = System.nanoTime();
273 final int count = mBitmaps.size();
274
275 for (int i = 0; i < count; i++) {
276 final Bitmap bitmap = mBitmaps.get(i);
277 if (atlas.pack(bitmap.getWidth(), bitmap.getHeight(), entry) != null) {
278 // We have more bitmaps to pack than the current configuration
279 // says, we were most likely not able to detect a change in the
280 // list of preloaded drawables, abort and delete the configuration
281 if (mapIndex >= mAtlasMap.length) {
282 deleteDataFile();
283 break;
284 }
285
286 canvas.save();
287 canvas.translate(entry.x, entry.y);
288 if (entry.rotated) {
289 canvas.translate(bitmap.getHeight(), 0.0f);
290 canvas.rotate(90.0f);
291 }
292 canvas.drawBitmap(bitmap, 0.0f, 0.0f, null);
293 canvas.restore();
John Reckf4faeac2015-03-05 13:50:31 -0800294 atlasMap[mapIndex++] = bitmap.getSkBitmap();
Romain Guy3b748a42013-04-17 18:54:38 -0700295 atlasMap[mapIndex++] = entry.x;
296 atlasMap[mapIndex++] = entry.y;
297 atlasMap[mapIndex++] = entry.rotated ? 1 : 0;
298 }
299 }
300
301 final long endRender = System.nanoTime();
302 if (mNativeBitmap != 0) {
303 result = nUploadAtlas(buffer, mNativeBitmap);
304 }
305
306 final long endUpload = System.nanoTime();
307 if (DEBUG_ATLAS) {
308 float renderDuration = (endRender - startRender) / 1000.0f / 1000.0f;
309 float uploadDuration = (endUpload - endRender) / 1000.0f / 1000.0f;
310 Log.d(LOG_TAG, String.format("Rendered atlas in %.2fms (%.2f+%.2fms)",
311 renderDuration + uploadDuration, renderDuration, uploadDuration));
312 }
313
314 } finally {
315 releaseCanvas(canvas);
316 }
317
318 return result;
319 }
320
321 /**
322 * Returns a Canvas for the specified buffer. If {@link #DEBUG_ATLAS_TEXTURE}
323 * is turned on, the returned Canvas will render into a local bitmap that
324 * will then be saved out to disk for debugging purposes.
325 * @param width
326 * @param height
327 */
328 private Canvas acquireCanvas(int width, int height) {
329 if (DEBUG_ATLAS_TEXTURE) {
330 mAtlasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
331 return new Canvas(mAtlasBitmap);
332 } else {
333 Canvas canvas = new Canvas();
334 mNativeBitmap = nAcquireAtlasCanvas(canvas, width, height);
335 return canvas;
336 }
337 }
338
339 /**
340 * Releases the canvas used to render into the buffer. Calling this method
341 * will release any resource previously acquired. If {@link #DEBUG_ATLAS_TEXTURE}
342 * is turend on, calling this method will write the content of the atlas
343 * to disk in /data/system/atlas.png for debugging.
344 */
345 private void releaseCanvas(Canvas canvas) {
346 if (DEBUG_ATLAS_TEXTURE) {
347 canvas.setBitmap(null);
348
349 File systemDirectory = new File(Environment.getDataDirectory(), "system");
350 File dataFile = new File(systemDirectory, "atlas.png");
351
352 try {
353 FileOutputStream out = new FileOutputStream(dataFile);
354 mAtlasBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
355 out.close();
356 } catch (FileNotFoundException e) {
357 // Ignore
358 } catch (IOException e) {
359 // Ignore
360 }
361
362 mAtlasBitmap.recycle();
363 mAtlasBitmap = null;
364 } else {
365 nReleaseAtlasCanvas(canvas, mNativeBitmap);
366 }
367 }
368 }
369
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000370 private static native long nAcquireAtlasCanvas(Canvas canvas, int width, int height);
371 private static native void nReleaseAtlasCanvas(Canvas canvas, long bitmap);
372 private static native boolean nUploadAtlas(GraphicBuffer buffer, long bitmap);
Romain Guy3b748a42013-04-17 18:54:38 -0700373
374 @Override
Romain Guy80b12fc2013-05-29 15:54:25 -0700375 public boolean isCompatible(int ppid) {
376 return ppid == android.os.Process.myPpid();
377 }
378
379 @Override
Romain Guy3b748a42013-04-17 18:54:38 -0700380 public GraphicBuffer getBuffer() throws RemoteException {
381 return mAtlasReady.get() ? mBuffer : null;
382 }
383
384 @Override
Ashok Bhat17ab38f2014-01-27 16:00:23 +0000385 public long[] getMap() throws RemoteException {
Romain Guy3b748a42013-04-17 18:54:38 -0700386 return mAtlasReady.get() ? mAtlasMap : null;
387 }
388
389 /**
390 * Finds the best atlas configuration to pack the list of supplied bitmaps.
391 * This method takes advantage of multi-core systems by spawning a number
392 * of threads equal to the number of available cores.
393 */
394 private static Configuration computeBestConfiguration(
395 ArrayList<Bitmap> bitmaps, int pixelCount) {
396 if (DEBUG_ATLAS) Log.d(LOG_TAG, "Computing best atlas configuration...");
397
398 long begin = System.nanoTime();
399 List<WorkerResult> results = Collections.synchronizedList(new ArrayList<WorkerResult>());
400
401 // Don't bother with an extra thread if there's only one processor
402 int cpuCount = Runtime.getRuntime().availableProcessors();
403 if (cpuCount == 1) {
404 new ComputeWorker(MIN_SIZE, MAX_SIZE, STEP, bitmaps, pixelCount, results, null).run();
405 } else {
ztenghui072be092015-04-01 13:26:08 -0700406 int start = MIN_SIZE + (cpuCount - 1) * STEP;
407 int end = MAX_SIZE;
Romain Guy3b748a42013-04-17 18:54:38 -0700408 int step = STEP * cpuCount;
409
410 final CountDownLatch signal = new CountDownLatch(cpuCount);
411
ztenghui072be092015-04-01 13:26:08 -0700412 for (int i = 0; i < cpuCount; i++, start -= STEP, end -= STEP) {
Romain Guy3b748a42013-04-17 18:54:38 -0700413 ComputeWorker worker = new ComputeWorker(start, end, step,
414 bitmaps, pixelCount, results, signal);
415 new Thread(worker, "Atlas Worker #" + (i + 1)).start();
416 }
417
418 try {
419 signal.await(10, TimeUnit.SECONDS);
420 } catch (InterruptedException e) {
421 Log.w(LOG_TAG, "Could not complete configuration computation");
422 return null;
423 }
424 }
425
426 // Maximize the number of packed bitmaps, minimize the texture size
427 Collections.sort(results, new Comparator<WorkerResult>() {
428 @Override
429 public int compare(WorkerResult r1, WorkerResult r2) {
430 int delta = r2.count - r1.count;
431 if (delta != 0) return delta;
432 return r1.width * r1.height - r2.width * r2.height;
433 }
434 });
435
436 if (DEBUG_ATLAS) {
437 float delay = (System.nanoTime() - begin) / 1000.0f / 1000.0f / 1000.0f;
ztenghui072be092015-04-01 13:26:08 -0700438 Log.d(LOG_TAG, String.format("Found best atlas configuration (out of %d) in %.2fs",
439 results.size(), delay));
Romain Guy3b748a42013-04-17 18:54:38 -0700440 }
441
442 WorkerResult result = results.get(0);
443 return new Configuration(result.type, result.width, result.height, result.count);
444 }
445
446 /**
447 * Returns the path to the file containing the best computed
448 * atlas configuration.
449 */
450 private static File getDataFile() {
451 File systemDirectory = new File(Environment.getDataDirectory(), "system");
452 return new File(systemDirectory, "framework_atlas.config");
453 }
454
455 private static void deleteDataFile() {
456 Log.w(LOG_TAG, "Current configuration inconsistent with assets list");
457 if (!getDataFile().delete()) {
458 Log.w(LOG_TAG, "Could not delete the current configuration");
459 }
460 }
461
462 private File getFrameworkResourcesFile() {
463 return new File(mContext.getApplicationInfo().sourceDir);
464 }
465
466 /**
467 * Returns the best known atlas configuration. This method will either
468 * read the configuration from disk or start a brute-force search
469 * and save the result out to disk.
470 */
471 private Configuration chooseConfiguration(ArrayList<Bitmap> bitmaps, int pixelCount,
472 String versionName) {
473 Configuration config = null;
474
475 final File dataFile = getDataFile();
476 if (dataFile.exists()) {
477 config = readConfiguration(dataFile, versionName);
478 }
479
480 if (config == null) {
481 config = computeBestConfiguration(bitmaps, pixelCount);
482 if (config != null) writeConfiguration(config, dataFile, versionName);
483 }
484
485 return config;
486 }
487
488 /**
489 * Writes the specified atlas configuration to the specified file.
490 */
491 private void writeConfiguration(Configuration config, File file, String versionName) {
492 BufferedWriter writer = null;
493 try {
494 writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
495 writer.write(getBuildIdentifier(versionName));
496 writer.newLine();
497 writer.write(config.type.toString());
498 writer.newLine();
499 writer.write(String.valueOf(config.width));
500 writer.newLine();
501 writer.write(String.valueOf(config.height));
502 writer.newLine();
503 writer.write(String.valueOf(config.count));
504 writer.newLine();
505 writer.write(String.valueOf(config.flags));
506 writer.newLine();
507 } catch (FileNotFoundException e) {
508 Log.w(LOG_TAG, "Could not write " + file, e);
509 } catch (IOException e) {
510 Log.w(LOG_TAG, "Could not write " + file, e);
511 } finally {
512 if (writer != null) {
513 try {
514 writer.close();
515 } catch (IOException e) {
516 // Ignore
517 }
518 }
519 }
520 }
521
522 /**
523 * Reads an atlas configuration from the specified file. This method
524 * returns null if an error occurs or if the configuration is invalid.
525 */
526 private Configuration readConfiguration(File file, String versionName) {
527 BufferedReader reader = null;
528 Configuration config = null;
529 try {
530 reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
531
532 if (checkBuildIdentifier(reader, versionName)) {
533 Atlas.Type type = Atlas.Type.valueOf(reader.readLine());
534 int width = readInt(reader, MIN_SIZE, MAX_SIZE);
535 int height = readInt(reader, MIN_SIZE, MAX_SIZE);
536 int count = readInt(reader, 0, Integer.MAX_VALUE);
537 int flags = readInt(reader, Integer.MIN_VALUE, Integer.MAX_VALUE);
538
539 config = new Configuration(type, width, height, count, flags);
540 }
541 } catch (IllegalArgumentException e) {
542 Log.w(LOG_TAG, "Invalid parameter value in " + file, e);
543 } catch (FileNotFoundException e) {
544 Log.w(LOG_TAG, "Could not read " + file, e);
545 } catch (IOException e) {
546 Log.w(LOG_TAG, "Could not read " + file, e);
547 } finally {
548 if (reader != null) {
549 try {
550 reader.close();
551 } catch (IOException e) {
552 // Ignore
553 }
554 }
555 }
556 return config;
557 }
558
559 private static int readInt(BufferedReader reader, int min, int max) throws IOException {
560 return Math.max(min, Math.min(max, Integer.parseInt(reader.readLine())));
561 }
562
563 /**
564 * Compares the next line in the specified buffered reader to the current
565 * build identifier. Returns whether the two values are equal.
566 *
567 * @see #getBuildIdentifier(String)
568 */
569 private boolean checkBuildIdentifier(BufferedReader reader, String versionName)
570 throws IOException {
571 String deviceBuildId = getBuildIdentifier(versionName);
572 String buildId = reader.readLine();
573 return deviceBuildId.equals(buildId);
574 }
575
576 /**
577 * Returns an identifier for the current build that can be used to detect
578 * likely changes to framework resources. The build identifier is made of
579 * several distinct values:
580 *
581 * build fingerprint/framework version name/file size of framework resources apk
582 *
583 * Only the build fingerprint should be necessary on user builds but
584 * the other values are useful to detect changes on eng builds during
585 * development.
586 *
587 * This identifier does not attempt to be exact: a new identifier does not
588 * necessarily mean the preloaded drawables have changed. It is important
589 * however that whenever the list of preloaded drawables changes, this
590 * identifier changes as well.
591 *
592 * @see #checkBuildIdentifier(java.io.BufferedReader, String)
593 */
594 private String getBuildIdentifier(String versionName) {
595 return SystemProperties.get("ro.build.fingerprint", "") + '/' + versionName + '/' +
596 String.valueOf(getFrameworkResourcesFile().length());
597 }
598
599 /**
600 * Atlas configuration. Specifies the algorithm, dimensions and flags to use.
601 */
602 private static class Configuration {
603 final Atlas.Type type;
604 final int width;
605 final int height;
606 final int count;
607 final int flags;
608
609 Configuration(Atlas.Type type, int width, int height, int count) {
610 this(type, width, height, count, Atlas.FLAG_DEFAULTS);
611 }
612
613 Configuration(Atlas.Type type, int width, int height, int count, int flags) {
614 this.type = type;
615 this.width = width;
616 this.height = height;
617 this.count = count;
618 this.flags = flags;
619 }
620
621 @Override
622 public String toString() {
623 return type.toString() + " (" + width + "x" + height + ") flags=0x" +
624 Integer.toHexString(flags) + " count=" + count;
625 }
626 }
627
628 /**
629 * Used during the brute-force search to gather information about each
630 * variant of the packing algorithm.
631 */
632 private static class WorkerResult {
633 Atlas.Type type;
634 int width;
635 int height;
636 int count;
637
638 WorkerResult(Atlas.Type type, int width, int height, int count) {
639 this.type = type;
640 this.width = width;
641 this.height = height;
642 this.count = count;
643 }
644
645 @Override
646 public String toString() {
647 return String.format("%s %dx%d", type.toString(), width, height);
648 }
649 }
650
651 /**
652 * A compute worker will try a finite number of variations of the packing
653 * algorithms and save the results in a supplied list.
654 */
655 private static class ComputeWorker implements Runnable {
656 private final int mStart;
657 private final int mEnd;
658 private final int mStep;
659 private final List<Bitmap> mBitmaps;
660 private final List<WorkerResult> mResults;
661 private final CountDownLatch mSignal;
662 private final int mThreshold;
663
664 /**
665 * Creates a new compute worker to brute-force through a range of
666 * packing algorithms variants.
667 *
668 * @param start The minimum texture width to try
669 * @param end The maximum texture width to try
670 * @param step The number of pixels to increment the texture width by at each step
671 * @param bitmaps The list of bitmaps to pack in the atlas
672 * @param pixelCount The total number of pixels occupied by the list of bitmaps
673 * @param results The list of results in which to save the brute-force search results
674 * @param signal Latch to decrement when this worker is done, may be null
675 */
676 ComputeWorker(int start, int end, int step, List<Bitmap> bitmaps, int pixelCount,
677 List<WorkerResult> results, CountDownLatch signal) {
678 mStart = start;
679 mEnd = end;
680 mStep = step;
681 mBitmaps = bitmaps;
682 mResults = results;
683 mSignal = signal;
684
685 // Minimum number of pixels we want to be able to pack
686 int threshold = (int) (pixelCount * PACKING_THRESHOLD);
687 // Make sure we can find at least one configuration
688 while (threshold > MAX_SIZE * MAX_SIZE) {
689 threshold >>= 1;
690 }
691 mThreshold = threshold;
692 }
693
694 @Override
695 public void run() {
696 if (DEBUG_ATLAS) Log.d(LOG_TAG, "Running " + Thread.currentThread().getName());
697
698 Atlas.Entry entry = new Atlas.Entry();
699 for (Atlas.Type type : Atlas.Type.values()) {
ztenghui072be092015-04-01 13:26:08 -0700700 for (int width = mEnd; width > mStart; width -= mStep) {
701 for (int height = MAX_SIZE; height > MIN_SIZE; height -= STEP) {
Romain Guy3b748a42013-04-17 18:54:38 -0700702 // If the atlas is not big enough, skip it
703 if (width * height <= mThreshold) continue;
704
705 final int count = packBitmaps(type, width, height, entry);
706 if (count > 0) {
707 mResults.add(new WorkerResult(type, width, height, count));
708 // If we were able to pack everything let's stop here
709 // Increasing the height further won't make things better
710 if (count == mBitmaps.size()) {
711 break;
712 }
713 }
714 }
715 }
716 }
717
718 if (mSignal != null) {
719 mSignal.countDown();
720 }
721 }
722
723 private int packBitmaps(Atlas.Type type, int width, int height, Atlas.Entry entry) {
724 int total = 0;
725 Atlas atlas = new Atlas(type, width, height);
726
727 final int count = mBitmaps.size();
728 for (int i = 0; i < count; i++) {
729 final Bitmap bitmap = mBitmaps.get(i);
730 if (atlas.pack(bitmap.getWidth(), bitmap.getHeight(), entry) != null) {
731 total++;
732 }
733 }
734
735 return total;
736 }
737 }
738}