Autodesk Forge RGraph扩展程序无法正常工作 [英] Autodesk forge RGraph extension not working properly

查看:99
本文介绍了Autodesk Forge RGraph扩展程序无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Autodesk Forge扩展(RGraph).我已按照中所述的步骤进行操作 http://adndevblog. typepad.com/cloud_and_mobile/2016/02/rgraph-chart-library-and-view-data-api.html

I have an Autodesk Forge extension(RGraph). I have followed the the steps as mentioned in http://adndevblog.typepad.com/cloud_and_mobile/2016/02/rgraph-chart-library-and-view-data-api.html

但是函数getLeafComponentsRec(parent)出现错误,错误将是Cannot read property 'children' of undefined.

But I get an error at the function getLeafComponentsRec(parent) and the error would be Cannot read property 'children' of undefined.

我也尝试根据我的知识修改整个扩展名,但是即使在那儿我也没有成功.我修改后的扩展名是这样的.

I have also tried to modify the whole extension according to my knowledge but I'm not successful even there. My modified extension would be something like this.

///////////////////////////////////////////////////////////////////////////////
// Autodesk.ADN.Viewing.Extension.Chart
// by Philippe Leefsma, July 2015
//
// Dependencies:
//
// Bootstrap: 3.3.5
// http://code.jquery.com/jquery-2.1.4.min.js
// https://rawgit.com/caolan/async/master/dist/async.min.js
// https://rawgit.com/nnnick/Chart.js/master/Chart.min.js
//
///////////////////////////////////////////////////////////////////////////////
AutodeskNamespace('Autodesk.ADN.Viewing.Extension.Chart');

Autodesk.ADN.Viewing.Extension.Chart.RGraph = function(viewer, options) {
  Autodesk.Viewing.Extension.call(this, viewer, options);

  var _self = this;
  var _elementIds = [];
  var _canvasId = null;
  var _components = null;
  var instanceTree;
  var rootId;
  var _graphType = 'pie';
  var _propName = 'label';

  _self.load = function() {

    viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function() {
      instanceTree = viewer.model.getData().instanceTree;
      rootId = this.rootId = instanceTree.getRootId();
      getAlldbIds(rootId);
      getAllLeafComponents(function(components) {
        _components = components;

        _elementIds.push(createDropdownMenu(
          'Graph Type', {
            top: 50,
            left: 330
          }, [{
            label: 'Pie',
            handler: function() {
              _graphType = 'pie';
              loadChartFromProperty(_graphType, _propName, _components);
            }
          }]
        ));


        getAvailableProperties(components, function(properties) {
          var menuItems = [];
          var labelIdx = 0;
          _propName = properties[0];
          properties.forEach(function(property, idx) {
            if (property === 'label') {
              labelIdx = idx;
              _propName = 'label';
            }

            menuItems.push({
              label: property,
              handler: function() {
                _propName = property;
                loadChartFromProperty(_graphType, _propName, _components);
              }
            })
          });

          _elementIds.push(createDropdownMenu(
            'Property', {
              top: 100,
              left: 330
            },
            menuItems,
            labelIdx));

          loadChartFromProperty(_graphType, _propName, _components);
        });
      });

      console.log('RGraph extension loaded');
      return true;
    });
  };

  ///////////////////////////////////////////////////////////////////////////
  // unload callback
  //
  ///////////////////////////////////////////////////////////////////////////
  _self.unload = function() {
    _elementIds.forEach(function(id) {

      $('#' + id).remove();
    });

    $('#' + _canvasId).remove();
    console.log('RGraph extension unloaded');
    return true;
  };

  /////////////////////////////////////////////////////////////
  ///Gets All DbId
  ///
  ////////////////////////////////////////////////////////////
  function getAlldbIds(rootId) {
    var alldbId = [];
    if (!rootId) {
      console.log(alldbId);
      return alldbId;
    }
    var queue = [];
    queue.push(rootId);
    while (queue.length > 0) {
      var node = queue.shift();
      alldbId.push(node);
      instanceTree.enumNodeChildren(node, function(childrenIds) {
        queue.push(childrenIds);
        //viewer.model.getProperties(childrenIds, function (props) {
        //var propertyname = props.name.split('[')[0];
        //  propsqueue.push(props.name.split('[')[0]);
        //});
      });

    }
    console.log(alldbId);
    //console.log(propsqueue);

  }

  //////////////////////////////////////////////////////////////////////////
  // loadChartFromProperty
  //
  ///////////////////////////////////////////////////////////////////////////
  function loadChartFromProperty(chartType, propName, components) {
    mapComponentsByPropName(propName, components, function(map) {
      // RGraph needs 2 arrays, at least: data & labels
      var data = [];
      var labels = [];
      for (var key in map) {
        data.push(map[key].length);
        labels.push(key);
      }

      // clear previous graphs and create a new canvas element
      $('#' + _canvasId).remove();
      _canvasId = guid();
      createOverlay(_canvasId);
      var graph;

      switch (chartType) {
        case 'pie':
          // Pie chart
          graph = new RGraph.Pie({
              id: _canvasId,
              data: data,
              options: {
                shadow: true,
                shadowOffsety: 7,
                shadowBlur: 25,
                strokestyle: 'rgba(0,0,0,0)',
                tooltips: labels, // let's use the labels as tooltips
                radius: 100
              }
            }).roundRobin({
              frames: 60
            })
            .grow({
              frames: 60
            });
      }

      // on click, let's zoom to the geometry
      graph.onclick = function(e, shape) {
        var key = shape.tooltip;
        viewer.fitToView(map[key]);
      };

      // on mouse move, highligh/isole the geometry
      graph.onmousemove = function(e, shape) {
        var key = shape.tooltip;
        viewer.isolate(map[key]);
      };
    });
  }

  ///////////////////////////////////////////////////////////////////////////
  // Creates overlay canvas element
  //
  ///////////////////////////////////////////////////////////////////////////
  function createOverlay(canvasId) {
    var html = [
      '<canvas class="graph" id="' + canvasId + '" width="300" height="300">',
      '</canvas>',
    ].join('\n');
    $(viewer.container).append(html);
  }

  ///////////////////////////////////////////////////////////////////////////
  // Maps components by property
  //
  ///////////////////////////////////////////////////////////////////////////
  function mapComponentsByPropName(propName, components, onResult) {
    var componentsMap = {};
    async.each(components,
      function(component, callback) {
        getPropertyValue(component, propName, function(value) {
          if (propName === 'label') {
            value = value.split(':')[0];
          }
          if (!componentsMap[value]) {
            componentsMap[value] = [];
          }
          componentsMap[value].push(component);
          callback();
        });
      },
      function(err) {
        onResult(componentsMap);
      });
  }
  ///////////////////////////////////////////////////////////////////////////
  // Gets all existing properties from components list
  //
  ///////////////////////////////////////////////////////////////////////////
  function getAvailableProperties(components, onResult) {
    var propertiesMap = {};
    async.each(components,
      function(component, callback) {
        viewer.getProperties(component, function(result) {
          for (var i = 0; i < result.properties.length; i++) {
            var prop = result.properties[i];
            propertiesMap[prop.displayName] = {};
          }
          callback();
        });
      },
      function(err) {
        onResult(Object.keys(propertiesMap));
      });
  }

  ///////////////////////////////////////////////////////////////////////////
  // Get all leaf components
  //
  ///////////////////////////////////////////////////////////////////////////
  function getAllLeafComponents(callback) {
    var alldbId = [];
    if (!rootId) {
      console.log(alldbId);
      return alldbId;
    }
    var queue = [];
    queue.push(rootId);
    while (queue.length > 0) {
      var node = queue.shift();
      alldbId.push(node);
      instanceTree.enumNodeChildren(node, function(childrenIds) {
        queue.push(childrenIds);
        //viewer.model.getProperties(childrenIds, function (props) {
        //var propertyname = props.name.split('[')[0];
        //  propsqueue.push(props.name.split('[')[0]);
        //});
      });

    }
    console.log(alldbId);
    callback(alldbId);
    viewer.getObjectTree(function(result) {
      var allLeafComponents = rootId;
      callback(allLeafComponents);
      console.log(allLeafComponents);
    });
  };

  ///////////////////////////////////////////////////////////////////////////
  // Get property value from display name
  //
  ///////////////////////////////////////////////////////////////////////////
  function getPropertyValue(dbId, displayName, callback) {
    function _cb(result) {
      if (result.properties) {
        for (var i = 0; i < result.properties.length; i++) {
          var prop = result.properties[i];
          if (prop.displayName === displayName) {
            callback(prop.displayValue);
            return;
          }
        }
        callback('undefined');
      }
    }
    viewer.getProperties(dbId, _cb);
  };

  ///////////////////////////////////////////////////////////////////////////
  // Generates random guid
  //
  ///////////////////////////////////////////////////////////////////////////
  function guid() {
    var d = new Date().getTime();
    var guid = 'xxxx-xxxx-xxxx-xxxx'.replace(
      /[xy]/g,
      function(c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
      });
    return guid;
  };
  ///////////////////////////////////////////////////////////////////////////
  // Creates dropdown menu from input
  //
  ///////////////////////////////////////////////////////////////////////////
  function createDropdownMenu(title, pos, menuItems, selectedItemIdx) {
    var labelId = guid();
    var menuId = guid();
    var listId = guid();
    var html = [
      '<div id ="' + menuId + '" class="dropdown chart-dropdown">',
      '<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">',
      '<label id="' + labelId + '" style="font: normal 14px Times New Roman">' + title + '</label>',
      '<span class="caret"></span>',
      '</button>',
      '<ul id="' + listId + '"class="dropdown-menu scrollable-menu" >',
      '</ul>',
      '</div>'
    ].join('\n');

    $(viewer.container).append(html);
    $('#' + menuId).css({
      'top': pos.top + 'px',
      'left': pos.left + 'px'
    });
    $('#' + labelId).text(title + ': ' + menuItems[selectedItemIdx || 0].label);
    menuItems.forEach(function(menuItem) {
      var itemId = guid();
      var itemHtml = '<li id="' + itemId + '"><a href="">' + menuItem.label + '</a></li>';
      $('#' + listId).append(itemHtml);
      $('#' + itemId).click(function(event) {
        event.preventDefault();
        menuItem.handler();
        $('#' + labelId).text(title + ': ' + menuItem.label);
      });
    });
    return menuId;
  }

  ///////////////////////////////////////////////////////////////////////////
  // dynamic css styles
  //
  ///////////////////////////////////////////////////////////////////////////
  var css = [
    'canvas.graph {',
    'top:10px;',
    'left:30px;',
    'width:300px;',
    'height:300px;',
    'position:absolute;',
    'overflow:hidden;',
    '}',

    'div.chart-dropdown {',
    'position: absolute;',
    '}',

    '.scrollable-menu {',
    'height: auto;',
    'max-height: 300px;',
    'overflow-x: hidden;',
    'overflow-y: scroll;',
    '}',

  ].join('\n');
  $('<style type="text/css">' + css + '</style>').appendTo('head');
};
Autodesk.ADN.Viewing.Extension.Chart.RGraph.prototype = Object.create(Autodesk.Viewing.Extension.prototype);

Autodesk.ADN.Viewing.Extension.Chart.RGraph.prototype.constructor = Autodesk.ADN.Viewing.Extension.Chart.RGraph;

Autodesk.Viewing.theExtensionManager.registerExtension('Autodesk.ADN.Viewing.Extension.Chart.RGraph', Autodesk.ADN.Viewing.Extension.Chart.RGraph);

在此修改后的代码中,我的扩展程序可以正常加载,甚至显示图表类型和属性的下拉列表.但是,当我选择它时,我没有得到图表.这里的问题存在于getAvailableProperties(components, onResult)函数中.我还注意到在createDropdownMenu函数中,开发人员工具没有达到断点.

In this modified code my extension loads fine and even shows the dropdowns for chart type and the properties. But when I select it I don't get the chart. Here the problem exists in the getAvailableProperties(components, onResult) function. Also I noticed that in the createDropdownMenu function the developer tool is not hitting the breakpoints.

我不知道我要去哪里.有人可以帮我吗? 预先感谢.

I don't know where I'm going wrong. Can someone help me over here? Thanks in advance.

推荐答案

此代码示例已过时,并且使用了不受支持的功能,在此处查看更多.

This code sample is outdated and using unsupported features, see more here.

您可以将getAllLeafComponents方法替换为:

function getAllLeafComponents(callback) {
    var cbCount = 0; // count pending callbacks
    var components = []; // store the results
    var tree; // the instance tree

    function getLeafComponentsRec(parent) {
        cbCount++;
        if (tree.getChildCount(parent) != 0) {
            tree.enumNodeChildren(parent, function (children) {
                getLeafComponentsRec(children);
            }, false);
        } else {
            components.push(parent);
        }
        if (--cbCount == 0) callback(components);
    }
    viewer.getObjectTree(function (objectTree) {
        tree = objectTree;
        var allLeafComponents = getLeafComponentsRec(tree.getRootId());
    });
}

这篇关于Autodesk Forge RGraph扩展程序无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆