1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "gpu/tools/compositor_model_bench/render_tree.h"
6
7#include <sstream>
8#include <vector>
9
10#include "base/file_util.h"
11#include "base/files/file_path.h"
12#include "base/json/json_reader.h"
13#include "base/json/json_writer.h"
14#include "base/logging.h"
15#include "base/memory/scoped_ptr.h"
16#include "base/values.h"
17
18#include "gpu/tools/compositor_model_bench/shaders.h"
19
20using base::JSONReader;
21using base::JSONWriter;
22using base::Value;
23using base::ReadFileToString;
24using std::string;
25using std::vector;
26
27GLenum TextureFormatFromString(std::string format) {
28  if (format == "RGBA")
29    return GL_RGBA;
30  if (format == "RGB")
31    return GL_RGB;
32  if (format == "LUMINANCE")
33    return GL_LUMINANCE;
34  return GL_INVALID_ENUM;
35}
36
37const char* TextureFormatName(GLenum format) {
38  switch (format) {
39    case GL_RGBA:
40      return "RGBA";
41    case GL_RGB:
42      return "RGB";
43    case GL_LUMINANCE:
44      return "LUMINANCE";
45    default:
46      return "(unknown format)";
47  }
48}
49
50int FormatBytesPerPixel(GLenum format) {
51  switch (format) {
52    case GL_RGBA:
53      return 4;
54    case GL_RGB:
55      return 3;
56    case GL_LUMINANCE:
57      return 1;
58    default:
59      return 0;
60  }
61}
62
63RenderNode::RenderNode() {
64}
65
66RenderNode::~RenderNode() {
67}
68
69void RenderNode::Accept(RenderNodeVisitor* v) {
70  v->BeginVisitRenderNode(this);
71  v->EndVisitRenderNode(this);
72}
73
74ContentLayerNode::ContentLayerNode() {
75}
76
77ContentLayerNode::~ContentLayerNode() {
78}
79
80void ContentLayerNode::Accept(RenderNodeVisitor* v) {
81  v->BeginVisitContentLayerNode(this);
82  typedef vector<RenderNode*>::iterator node_itr;
83  for (node_itr i = children_.begin(); i != children_.end(); ++i) {
84    (*i)->Accept(v);
85  }
86  v->EndVisitContentLayerNode(this);
87}
88
89CCNode::CCNode() {
90}
91
92CCNode::~CCNode() {
93}
94
95void CCNode::Accept(RenderNodeVisitor* v) {
96  v->BeginVisitCCNode(this);
97  v->EndVisitCCNode(this);
98}
99
100RenderNodeVisitor::~RenderNodeVisitor() {
101}
102
103void RenderNodeVisitor::BeginVisitContentLayerNode(ContentLayerNode* v) {
104  this->BeginVisitRenderNode(v);
105}
106
107void RenderNodeVisitor::BeginVisitCCNode(CCNode* v) {
108  this->BeginVisitRenderNode(v);
109}
110
111void RenderNodeVisitor::EndVisitRenderNode(RenderNode* v) {
112}
113
114void RenderNodeVisitor::EndVisitContentLayerNode(ContentLayerNode* v) {
115  this->EndVisitRenderNode(v);
116}
117
118void RenderNodeVisitor::EndVisitCCNode(CCNode* v) {
119  this->EndVisitRenderNode(v);
120}
121
122RenderNode* InterpretNode(DictionaryValue* node);
123
124std::string ValueTypeAsString(Value::Type type) {
125  switch (type) {
126    case Value::TYPE_NULL:
127      return "NULL";
128    case Value::TYPE_BOOLEAN:
129      return "BOOLEAN";
130    case Value::TYPE_INTEGER:
131      return "INTEGER";
132    case Value::TYPE_DOUBLE:
133      return "DOUBLE";
134    case Value::TYPE_STRING:
135      return "STRING";
136    case Value::TYPE_BINARY:
137      return "BINARY";
138    case Value::TYPE_DICTIONARY:
139      return "DICTIONARY";
140    case Value::TYPE_LIST:
141      return "LIST";
142    default:
143      return "(UNKNOWN TYPE)";
144  }
145}
146
147// Makes sure that the key exists and has the type we expect.
148bool VerifyDictionaryEntry(DictionaryValue* node,
149                           const std::string& key,
150                           Value::Type type) {
151  if (!node->HasKey(key)) {
152    LOG(ERROR) << "Missing value for key: " << key;
153    return false;
154  }
155
156  Value* child;
157  node->Get(key, &child);
158  if (!child->IsType(type)) {
159    LOG(ERROR) << key << " did not have the expected type "
160      "(expected " << ValueTypeAsString(type) << ")";
161    return false;
162  }
163
164  return true;
165}
166
167// Makes sure that the list entry has the type we expect.
168bool VerifyListEntry(ListValue* l,
169                     int idx,
170                     Value::Type type,
171                     const char* listName = 0) {
172  // Assume the idx is valid (since we'll be able to generate a better
173  // error message for this elsewhere.)
174  Value* el;
175  l->Get(idx, &el);
176  if (!el->IsType(type)) {
177    LOG(ERROR) << (listName ? listName : "List") << "element " << idx <<
178      " did not have the expected type (expected " <<
179      ValueTypeAsString(type) << ")\n";
180    return false;
181  }
182
183  return true;
184}
185
186bool InterpretCommonContents(DictionaryValue* node, RenderNode* c) {
187  if (!VerifyDictionaryEntry(node, "layerID", Value::TYPE_INTEGER) ||
188      !VerifyDictionaryEntry(node, "width", Value::TYPE_INTEGER) ||
189      !VerifyDictionaryEntry(node, "height", Value::TYPE_INTEGER) ||
190      !VerifyDictionaryEntry(node, "drawsContent", Value::TYPE_BOOLEAN) ||
191      !VerifyDictionaryEntry(node, "targetSurfaceID", Value::TYPE_INTEGER) ||
192      !VerifyDictionaryEntry(node, "transform", Value::TYPE_LIST)
193    ) {
194    return false;
195  }
196
197  int layerID;
198  node->GetInteger("layerID", &layerID);
199  c->set_layerID(layerID);
200  int width;
201  node->GetInteger("width", &width);
202  c->set_width(width);
203  int height;
204  node->GetInteger("height", &height);
205  c->set_height(height);
206  bool drawsContent;
207  node->GetBoolean("drawsContent", &drawsContent);
208  c->set_drawsContent(drawsContent);
209  int targetSurface;
210  node->GetInteger("targetSurfaceID", &targetSurface);
211  c->set_targetSurface(targetSurface);
212
213  ListValue* transform;
214  node->GetList("transform", &transform);
215  if (transform->GetSize() != 16) {
216    LOG(ERROR) << "4x4 transform matrix did not have 16 elements";
217    return false;
218  }
219  float transform_mat[16];
220  for (int i = 0; i < 16; ++i) {
221    if (!VerifyListEntry(transform, i, Value::TYPE_DOUBLE, "Transform"))
222      return false;
223    double el;
224    transform->GetDouble(i, &el);
225    transform_mat[i] = el;
226  }
227  c->set_transform(transform_mat);
228
229  if (node->HasKey("tiles")) {
230    if (!VerifyDictionaryEntry(node, "tiles", Value::TYPE_DICTIONARY))
231      return false;
232    DictionaryValue* tiles_dict;
233    node->GetDictionary("tiles", &tiles_dict);
234    if (!VerifyDictionaryEntry(tiles_dict, "dim", Value::TYPE_LIST))
235      return false;
236    ListValue* dim;
237    tiles_dict->GetList("dim", &dim);
238    if (!VerifyListEntry(dim, 0, Value::TYPE_INTEGER, "Tile dimension") ||
239        !VerifyListEntry(dim, 1, Value::TYPE_INTEGER, "Tile dimension")) {
240      return false;
241    }
242    int tile_width;
243    dim->GetInteger(0, &tile_width);
244    c->set_tile_width(tile_width);
245    int tile_height;
246    dim->GetInteger(1, &tile_height);
247    c->set_tile_height(tile_height);
248
249    if (!VerifyDictionaryEntry(tiles_dict, "info", Value::TYPE_LIST))
250      return false;
251    ListValue* tiles;
252    tiles_dict->GetList("info", &tiles);
253    for (unsigned int i = 0; i < tiles->GetSize(); ++i) {
254      if (!VerifyListEntry(tiles, i, Value::TYPE_DICTIONARY, "Tile info"))
255        return false;
256      DictionaryValue* tdict;
257      tiles->GetDictionary(i, &tdict);
258
259      if (!VerifyDictionaryEntry(tdict, "x", Value::TYPE_INTEGER) ||
260          !VerifyDictionaryEntry(tdict, "y", Value::TYPE_INTEGER)) {
261        return false;
262      }
263      Tile t;
264      tdict->GetInteger("x", &t.x);
265      tdict->GetInteger("y", &t.y);
266      if (tdict->HasKey("texID")) {
267        if (!VerifyDictionaryEntry(tdict, "texID", Value::TYPE_INTEGER))
268          return false;
269        tdict->GetInteger("texID", &t.texID);
270      } else {
271        t.texID = -1;
272      }
273      c->add_tile(t);
274    }
275  }
276  return true;
277}
278
279bool InterpretCCData(DictionaryValue* node, CCNode* c) {
280  if (!VerifyDictionaryEntry(node, "vertex_shader", Value::TYPE_STRING) ||
281      !VerifyDictionaryEntry(node, "fragment_shader", Value::TYPE_STRING) ||
282      !VerifyDictionaryEntry(node, "textures", Value::TYPE_LIST)) {
283    return false;
284  }
285  string vertex_shader_name, fragment_shader_name;
286  node->GetString("vertex_shader", &vertex_shader_name);
287  node->GetString("fragment_shader", &fragment_shader_name);
288
289  c->set_vertex_shader(ShaderIDFromString(vertex_shader_name));
290  c->set_fragment_shader(ShaderIDFromString(fragment_shader_name));
291  ListValue* textures;
292  node->GetList("textures", &textures);
293  for (unsigned int i = 0; i < textures->GetSize(); ++i) {
294    if (!VerifyListEntry(textures, i, Value::TYPE_DICTIONARY, "Tex list"))
295      return false;
296    DictionaryValue* tex;
297    textures->GetDictionary(i, &tex);
298
299    if (!VerifyDictionaryEntry(tex, "texID", Value::TYPE_INTEGER) ||
300        !VerifyDictionaryEntry(tex, "height", Value::TYPE_INTEGER) ||
301        !VerifyDictionaryEntry(tex, "width", Value::TYPE_INTEGER) ||
302        !VerifyDictionaryEntry(tex, "format", Value::TYPE_STRING)) {
303      return false;
304    }
305    Texture t;
306    tex->GetInteger("texID", &t.texID);
307    tex->GetInteger("height", &t.height);
308    tex->GetInteger("width", &t.width);
309
310    string formatName;
311    tex->GetString("format", &formatName);
312    t.format = TextureFormatFromString(formatName);
313    if (t.format == GL_INVALID_ENUM) {
314      LOG(ERROR) << "Unrecognized texture format in layer " << c->layerID() <<
315        " (format: " << formatName << ")\n"
316        "The layer had " << textures->GetSize() << " children.";
317      return false;
318    }
319
320    c->add_texture(t);
321  }
322
323  if (c->vertex_shader() == SHADER_UNRECOGNIZED) {
324    LOG(ERROR) << "Unrecognized vertex shader name, layer " << c->layerID() <<
325      " (shader: " << vertex_shader_name << ")";
326    return false;
327  }
328
329  if (c->fragment_shader() == SHADER_UNRECOGNIZED) {
330    LOG(ERROR) << "Unrecognized fragment shader name, layer " << c->layerID() <<
331      " (shader: " << fragment_shader_name << ")";
332    return false;
333  }
334
335  return true;
336}
337
338RenderNode* InterpretContentLayer(DictionaryValue* node) {
339  ContentLayerNode* n = new ContentLayerNode;
340  if (!InterpretCommonContents(node, n))
341    return NULL;
342
343  if (!VerifyDictionaryEntry(node, "type", Value::TYPE_STRING) ||
344      !VerifyDictionaryEntry(node, "skipsDraw", Value::TYPE_BOOLEAN) ||
345      !VerifyDictionaryEntry(node, "children", Value::TYPE_LIST)) {
346    return NULL;
347  }
348
349  string type;
350  node->GetString("type", &type);
351  DCHECK_EQ(type, "ContentLayer");
352  bool skipsDraw;
353  node->GetBoolean("skipsDraw", &skipsDraw);
354  n->set_skipsDraw(skipsDraw);
355
356  ListValue* children;
357  node->GetList("children", &children);
358  for (unsigned int i = 0; i < children->GetSize(); ++i) {
359    DictionaryValue* childNode;
360    children->GetDictionary(i, &childNode);
361    RenderNode* child = InterpretNode(childNode);
362    if (child)
363      n->add_child(child);
364  }
365
366  return n;
367}
368
369RenderNode* InterpretCanvasLayer(DictionaryValue* node) {
370  CCNode* n = new CCNode;
371  if (!InterpretCommonContents(node, n))
372    return NULL;
373
374  if (!VerifyDictionaryEntry(node, "type", Value::TYPE_STRING)) {
375    return NULL;
376  }
377
378  string type;
379  node->GetString("type", &type);
380  assert(type == "CanvasLayer");
381
382  if (!InterpretCCData(node, n))
383    return NULL;
384
385  return n;
386}
387
388RenderNode* InterpretVideoLayer(DictionaryValue* node) {
389  CCNode* n = new CCNode;
390  if (!InterpretCommonContents(node, n))
391    return NULL;
392
393  if (!VerifyDictionaryEntry(node, "type", Value::TYPE_STRING)) {
394    return NULL;
395  }
396
397  string type;
398  node->GetString("type", &type);
399  assert(type == "VideoLayer");
400
401  if (!InterpretCCData(node, n))
402    return NULL;
403
404  return n;
405}
406
407RenderNode* InterpretImageLayer(DictionaryValue* node) {
408  CCNode* n = new CCNode;
409  if (!InterpretCommonContents(node, n))
410    return NULL;
411
412  if (!VerifyDictionaryEntry(node, "type", Value::TYPE_STRING)) {
413    return NULL;
414  }
415
416  string type;
417  node->GetString("type", &type);
418  assert(type == "ImageLayer");
419
420  if (!InterpretCCData(node, n))
421    return NULL;
422
423  return n;
424}
425
426RenderNode* InterpretNode(DictionaryValue* node) {
427  if (!VerifyDictionaryEntry(node, "type", Value::TYPE_STRING)) {
428    return NULL;
429  }
430
431  string type;
432  node->GetString("type", &type);
433  if (type == "ContentLayer")
434    return InterpretContentLayer(node);
435  if (type == "CanvasLayer")
436    return InterpretCanvasLayer(node);
437  if (type == "VideoLayer")
438    return InterpretVideoLayer(node);
439  if (type == "ImageLayer")
440    return InterpretImageLayer(node);
441
442
443  string outjson;
444  JSONWriter::WriteWithOptions(node, base::JSONWriter::OPTIONS_PRETTY_PRINT,
445                               &outjson);
446  LOG(ERROR) << "Unrecognized node type! JSON:\n\n"
447      "-----------------------\n" <<
448      outjson <<
449      "-----------------------";
450
451  return NULL;
452}
453
454RenderNode* BuildRenderTreeFromFile(const base::FilePath& path) {
455  LOG(INFO) << "Reading " << path.LossyDisplayName();
456  string contents;
457  if (!ReadFileToString(path, &contents))
458    return NULL;
459
460  scoped_ptr<Value> root;
461  int error_code = 0;
462  string error_message;
463  root.reset(JSONReader::ReadAndReturnError(contents,
464            base::JSON_ALLOW_TRAILING_COMMAS,
465            &error_code,
466            &error_message));
467  if (!root.get()) {
468    LOG(ERROR) << "Failed to parse JSON file " << path.LossyDisplayName() <<
469        "\n(" << error_message << ")";
470    return NULL;
471  }
472
473  if (root->IsType(Value::TYPE_DICTIONARY)) {
474    DictionaryValue* v = static_cast<DictionaryValue*>(root.get());
475    RenderNode* tree = InterpretContentLayer(v);
476    return tree;
477  } else {
478    LOG(ERROR) << path.LossyDisplayName() <<
479        " doesn not encode a JSON dictionary.";
480    return NULL;
481  }
482}
483
484