load_ac3d.m 23.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
classdef load_ac3d
    % Class for GA model info

% <ITA-Toolbox>
% This file is part of the application Raven for the ITA-Toolbox. All rights reserved.
% You can find the license for this m-file in the application folder.
% </ITA-Toolbox>

    
    properties (GetAccess = 'public', SetAccess = 'public')
        nodes = [];              % numeric array with x,y,z coords of nodes with size(n,3)
    end
    
    properties (GetAccess = 'private', SetAccess = 'private')
        modelFilename = '';
        polygons = {};           % cell-array, each cell specifies all
        % nodes of one polygon in a numeric array
        bcGroups = {};           % of class type: gaGroup()
        totalVolume = -1;
        totalSurface = -1;
        
        transparency = 0.1;
    end
    
    methods
        
        % CONSTRUCTOR
        function obj = load_ac3d(filename)
            if nargin > 0
                obj = obj.readAc3DModelFile(filename);
            end
        end % Constructor
        
        % OTHER FUNCTIONS
        function obj = readAc3DModelFile(obj, fullFilename)
            
            if exist(fullFilename, 'file')
%                 ac3d_import = importdata(fullfile(pwd, fullFilename));
                ac3d_import = importdata(fullFilename);
                obj.modelFilename = fullFilename;
            else
                error('The specified file does not exist!');
            end
            ac3d = ac3d_import.textdata; % nur textdata von "importdata" interessant
            
            
            % Materialnamen und Farben
            
            mat_rows  = find(strcmp(ac3d,'MATERIAL')==1);  % Zeilenindizes der Materialien
            MatNames  = ac3d(mat_rows,2);                  % Cell der Material Namen
            MatColors = str2double(ac3d(mat_rows,4:6));    % Matrix der RGB Material Farben

                        
            % Vertizes Koordinaten finden
            
            % Es wird davon ausgegangen, dass bei jedem Objekt einmal der Begriff
            % "numvert" auftaucht, die Lnge von vert_rows ist daher auch mit der
            % Anzahl der Objekte in der ac3d Datei identisch.
            % Die find Funktion liefert dabei die Zeilennummer, in der "numvert" steht.
            % In die vertex_cell werden fr jedes Objekt alle Koordinaten der Vertizes
            % geschrieben.
            % Hierbei wird ber die ac3d Dateistruktur der Anfang und das Ende der
            % Liste der Vertizes ber die jeweilige Anzahl der Vertizes pro Objekt
            % angegeben.
            
            % Orientierung der Koordinatenbasis            
            loc_rows       = find(strcmp(ac3d,'loc')==1);             % Zeilenindizes der Basen
            vert_rows      = find(strcmp(ac3d,'numvert')==1);    % findet die Zeilenindizes der Zeilen mit 'numvert'
            numVertsInObj  = str2double(ac3d(vert_rows,2));
            vertex_cell    = cell(1, length(vert_rows));         % preallocation of memory
            translation_vector = cell(1, length(vert_rows)); % preallocation of memory
            
            for i = 1:length(vert_rows)
                % Speichere alle Vertex Koordinaten in (nx3) numerical arrays.
                % Jede Cell in vertex_cell enthlt die Knoten fr ein Objekt
                vertex_cell{i} = str2double(ac3d((vert_rows(i)+1):(vert_rows(i)+numVertsInObj(i)),1:3));
                
                if size(vert_rows,1) == size(loc_rows,1)
                    translation_vector{i} = str2double(ac3d(loc_rows(i),2:4));
                else
                    translation_vector{i} = [0 0 0];
                end
            end
            
            %wird spter fr die richtige Zuordnung der Knoten Liste bentigt
            globalNumOfFirstVertexInObj = ones(length(vertex_cell),1);
            for i = 2:length(globalNumOfFirstVertexInObj)
                globalNumOfFirstVertexInObj(i) = sum(numVertsInObj(1:(i-1))) + 1;
            end
            
            % Material zuordnen
            
            % Hier werden den unterschiedlichen Polygonen die verschiedenen Materialien
            % zugeordnet.
            % Jedesmal wenn ein "mat" in der ac3d Datei auftaucht, handelt es sich um
            % ein neues Polygon (zumindest in den meisten Dateien).
            % In matnum_rows befinden sich alle Zeilennummern, in denen ein "mat"
            % auftaucht.
            % in matnum_rows_cell sind diese Zeilennummern den unterschiedlichen
            % Materialien zugeordnet.
            
            matnum_rows = find(strcmp(ac3d,'mat')==1);           % alle Materialzuordnungen fr die einzelnen Polygone finden
            matnum_rows_cell = cell(1, length(MatNames));
            for i = 1:length(MatNames)                           % speichert zeilen der unterschiedlichen mat NUMMER fr die unterschiedlichen Materialien ab
                % jede cell in matnum_rows enthlt die Zeilenindizes aller Polygone,
                % die zum Material mit der Nummer i gehren
                matnum_rows_cell{i} = matnum_rows( strcmpi(ac3d(matnum_rows,2),num2str(i-1)) );
            end
            
            % Datenstruktur erzeugen
            
            for i=1:length(MatNames)
                obj.bcGroups{i}.name     = MatNames{i};
                obj.bcGroups{i}.color    = MatColors(i,:);
                obj.bcGroups{i}.polygons = cell( length(matnum_rows_cell{i}),1);
                obj.bcGroups{i}.surface  = 0;
            end
            
            obj.nodes = [];
            
            for i = 1:length(vertex_cell)
                localCoordToWorldCoord = vertex_cell{i} + ones(size(vertex_cell{i},1),1)*translation_vector{i};
                obj.nodes = [obj.nodes; localCoordToWorldCoord];
            end
            
            
            % Bestimmung von Anfangs und Endzeilen der Objekte in der ac3d Datei ber numvert
            
            object_start = vert_rows;
            object_end   = vert_rows;
            for i = 1:(length(vert_rows)-1)
                object_end(i) = object_start(i+1);
            end
            object_end(end) = length(ac3d(:,1));
            
            
            % Alle Daten der Datenstruktur zuordnen
            % hier wird ber die objID sichergestellt, dass die richtigen Vertizes
            % verwendet werden
            globalIdx = 1;
            for matID = 1:length(MatNames) %Materialien durchgehen
                for objID = 1:length(vert_rows) %ac3d objekte durchgehen
                    for polyID = 1:length(matnum_rows_cell{matID}) % Anzahl der Polygone des Materials
                        if matnum_rows_cell{matID}(polyID) < object_end(objID) && matnum_rows_cell{matID}(polyID) > object_start(objID) %Vertex vom richtigen Objekt
                            numNodesOfPoly = str2double( ac3d(matnum_rows_cell{matID}(polyID)+1,2));
                            lineIdxOfFirstPolyNode = matnum_rows_cell{matID}(polyID) + 2;
                            lineIdxOfLastPolyNode  = matnum_rows_cell{matID}(polyID) + 1 + numNodesOfPoly;
                            localNodeObjectIDs = str2double( ac3d( lineIdxOfFirstPolyNode : lineIdxOfLastPolyNode ,1) );
                            obj.bcGroups{matID}.polygons{polyID} = localNodeObjectIDs + globalNumOfFirstVertexInObj(objID);
                            obj.polygons{globalIdx} = localNodeObjectIDs + globalNumOfFirstVertexInObj(objID);
                            globalIdx = globalIdx+1;
                        end
                    end
                end
            end
            
            
            % Dreiecksberechnung und Flchenberechnung
            % durch Triangulisieren und Satz des Heron
            % Triangulisation: Polygon wird in Dreiecke unterteilt
            % Satz des Heron: Flche eines Dreiecks A = 1/4 sqrt( (a+b+c)*(a+b-c)*(-a+b+c)*(a-b+c) )
            
            triaID = 1;
            for matID = 1:length(obj.bcGroups)
                for polyID = 1:length(obj.bcGroups{matID}.polygons)
                    for vertID = 1:(length(obj.bcGroups{matID}.polygons{polyID}(:,1))-2)
                        
                        node1 = obj.nodes(obj.bcGroups{matID}.polygons{polyID}(1       ),:);
                        node2 = obj.nodes(obj.bcGroups{matID}.polygons{polyID}(vertID+1),:);
                        node3 = obj.nodes(obj.bcGroups{matID}.polygons{polyID}(vertID+2),:);
                        
                        % Dreieck nach Triangulation abspeichern
                        triangles{triaID} = [node1;node2;node3];
                        
                        % Flchenberechnung fr Dreieck
                        a = norm( node1  - node2 );
                        b = norm( node1  - node3 );
                        c = norm( node2  - node3 );
                        surfTriangles(triaID) = real( 1/4 * sqrt( (a+b+c) * (-a+b+c) * (a-b+c) * (a+b-c) ) );
                        
                        % Normalenberechnung fr Dreieck
                        if norm( cross( (node2-node1), (node3-node1) ) ) == 0 % Schutz gegen Krppel Linien Polygone
                            normals{triaID} = [0 0 0];
                        else
                            normals{triaID} = cross( (node2-node1), (node3-node1) ) / norm( cross( (node2-node1), (node3-node1) ) );
                        end
                        
                        obj.bcGroups{matID}.surface = obj.bcGroups{matID}.surface + surfTriangles(triaID);
                        
                        % Index inkrement
                        triaID = triaID+1;
                    end
                end
            end
            
            obj.totalSurface = sum(surfTriangles);
            
            % Volumenberechnung aus Dreiecken nach
            % http://de.wikipedia.org/wiki/Volumen
            volume = 0;
            
            for i = 1:length(triangles)
                %     for j = 1:3
                volume = volume + 1/3 * surfTriangles(i) * normals{i} * sum(triangles{i})';
                %     end
            end
            volume = volume/3;
            obj.totalVolume = volume;
            
        end  % function readAc3DModelFile()
        
        
        function plotModel(obj, axes2Plot, component2axesMapping, wireframe)
            
            % colors = [ 1.0 0.0 0.0 0.5 0.5 0.0 0.5 0.5 1.0 1.0 0.0 0.5 0.0 0.5 1.0 0.1 0.3 0.5 0.7 0.9;
            %     0.0 1.0 0.0 0.5 0.0 0.5 0.5 1.0 0.5 0.5 1.0 0.0 0.5 1.0 0.0 0.1 0.3 0.5 0.7 0.9;
            %     0.0 0.0 1.0 0.0 0.5 0.5 1.0 0.5 0.5 0.0 0.5 1.0 1.0 0.5 0.5 0.1 0.3 0.5 0.7 0.9  ];
            
            if nargin < 4
                wireframe = 0;
            end
            
            if nargin < 3
                component2axesMapping = [3 1 2];    % x y z -> z x y  (openGL has Y pointing upwards while matlab has Z pointing upwards
            end
            
            invertAxes = sign(component2axesMapping);
            component2axesMapping = abs(component2axesMapping);
            
            % Determine where to Plot
            if (nargin > 1)
                ax = axes2Plot;
                set(gcf, 'CurrentAxes', ax);
                cameratoolbar(gcf, 'show')
                set(gcf, 'Renderer', 'OpenGL');
%                 cla(ax, 'reset');
            else
                h_fig = figure;
                ax = axes;
                set(h_fig, 'CurrentAxes', ax);
                cameratoolbar(h_fig, 'show')
                set(h_fig, 'Renderer', 'OpenGL');
            end
            
            if wireframe
                % display wireframe model
                hold all;
                for polyID = 1:numel(obj.polygons)
                    polyNodes = obj.polygons{polyID}(:,1);
                    line( obj.nodes([polyNodes; polyNodes(1)],component2axesMapping(1)) * invertAxes(1), ...
                        obj.nodes([polyNodes; polyNodes(1)],component2axesMapping(2)) * invertAxes(2), ...
                        obj.nodes([polyNodes; polyNodes(1)],component2axesMapping(3)) * invertAxes(3), ...
                        'Color', [.3 .7 .3]);
                end
            else
                % display GA model
                hold all
                for polyID = 1:numel(obj.polygons)
                    polyNodes = obj.polygons{polyID}(:,1);
                    patch( obj.nodes(polyNodes,component2axesMapping(1)) * invertAxes(1), ...
                        obj.nodes(polyNodes,component2axesMapping(2)) * invertAxes(2), ...
                        obj.nodes(polyNodes,component2axesMapping(3)) * invertAxes(3), ...
                        [0.5 0.5 0.5], ...
                        'FaceAlpha', obj.transparency );
                end

                % Plot Boundary Groups
                for groupID = 1:numel(obj.bcGroups)
                    for polyID = 1:length(obj.bcGroups{groupID}.polygons)
                        patch( obj.nodes(obj.bcGroups{groupID}.polygons{polyID}(:,1),component2axesMapping(1)) * invertAxes(1), ...
                            obj.nodes(obj.bcGroups{groupID}.polygons{polyID}(:,1),component2axesMapping(2)) * invertAxes(2), ...
                            obj.nodes(obj.bcGroups{groupID}.polygons{polyID}(:,1),component2axesMapping(3)) * invertAxes(3), ...
                            obj.bcGroups{groupID}.color, ...
                            'FaceAlpha', obj.transparency );
                    end
                end
%                 alpha( gca, obj.transparency );
            end
            
             axis(ax, 'off');
             axis(ax, 'equal');
            
        end
        
        function V = getVolume(obj)            
            V = obj.totalVolume;
        end
        
        function S = getSurface(obj)
            S = obj.totalSurface;
        end
       
        function [A, S] = getEquivalentAbsorptionArea_sabine(obj, material_path, portal_surface_materials)
            if nargin < 2
                material_path = '..\RavenDatabase\MaterialDatabase';
            end
            countPortals = 1;
            
            S = 0; %surface area (scalar)
            for matID = 1:length(obj.bcGroups)
                S = S + obj.bcGroups{matID}.surface;                % scalar
            end
            
            A = 0; %equivalent absorption area (vector over frequency)
            for matID = 1:length(obj.bcGroups)
                if isempty(strfind(obj.bcGroups{matID}.name, 'Portal'))
                    absorption = readRavenMaterial(obj.bcGroups{matID}.name, material_path);
                    if isempty(absorption)
                        error(['Material "' obj.bcGroups{matID}.name '" is not defined yet. Unable to compute absorption.']);
                    end
                else
                    if nargin < 3
                        error('Error! This model has portals, but no materialnames were given for the portal surface materials.');
                    end
                    absorption = readRavenMaterial(portal_surface_materials{countPortals}, material_path);
                    countPortals = countPortals + 1;
                    if isempty(absorption)
                        error(['Material "' portal_surface_materials{countPortals} '" is not defined yet. Unable to compute absorption.']);
                    end
                end                
                
                A = A + obj.bcGroups{matID}.surface .* absorption;   % vector                
            end            
        end

        function [A, S] = getEquivalentAbsorptionArea_eyring(obj, material_path, portal_surface_materials)
            if nargin < 2
                material_path = '..\RavenDatabase\MaterialDatabase';
            end
            countPortals = 1;
            
            S = 0; %surface area (scalar)
            for matID = 1:length(obj.bcGroups)
                S = S + obj.bcGroups{matID}.surface;                % scalar
            end
            
            A_tmp = 0; %equivalent absorption area (vector over frequency)
            for matID = 1:length(obj.bcGroups)
                if isempty(strfind(obj.bcGroups{matID}.name, 'Portal'))
                    absorption = readRavenMaterial(obj.bcGroups{matID}.name, material_path);
                    if isempty(absorption)
                        error(['Material "' obj.bcGroups{matID}.name '" is not defined yet. Unable to compute absorption.']);
                    end
                else
                    if nargin < 3
                        error('Error! This model has portals, but no materialnames were given for the portal surface materials.');
                    end
                    absorption = readRavenMaterial(portal_surface_materials{countPortals}, material_path);
                    countPortals = countPortals + 1;
                    if isempty(absorption)
                        error(['Material "' portal_surface_materials{countPortals} '" is not defined yet. Unable to compute absorption.']);
                    end
                end                
                
                A_tmp = A_tmp + obj.bcGroups{matID}.surface .* absorption ./ S;   % vector                
            end
            A = -S .* log(1 - A_tmp);            
        end
        
360 361

        
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        function [A, S] = getEquivalentAbsorptionArea(obj)
            [A, S] = obj.getEquivalentAbsorptionArea_sabine();
        end
        
        function RT = getReverbTime(obj, material_path, sabine_or_eyring, airAbsorption, portal_surface_materials)
            if nargin < 3
                airAbsorption = zeros(1,31);
            end
            if nargin < 3
                sabine_or_eyring = 'eyring';
            end
            if nargin < 2
                material_path = '..\RavenDatabase\MaterialDatabase';
            end
               
            if nargin > 4
                if strcmp(sabine_or_eyring, 'eyring')
                    [A, S] = obj.getEquivalentAbsorptionArea_eyring(material_path, portal_surface_materials);
                else
                    if ~strcmp(sabine_or_eyring, 'sabine')
                        disp('Given method not found. Define "sabine" or "eyring" as method. Using Sabine'' formula now.');
                    end
                    [A, S] = obj.getEquivalentAbsorptionArea_sabine(material_path, portal_surface_materials);
                end
            else
                if strcmp(sabine_or_eyring, 'eyring')
                    [A, S] = obj.getEquivalentAbsorptionArea_eyring(material_path);
                else
                    if ~strcmp(sabine_or_eyring, 'sabine')
                        disp('Given method not found. Define "sabine" or "eyring" as method. Using Sabine'' formula now.');
                    end
                    [A, S] = obj.getEquivalentAbsorptionArea_sabine(material_path);
                end
            end
            
            %RT = 0.163 .* obj.totalVolume ./ A;
           % RT = (2.76 / sqrt(273.15 + room_temperature)) .* (obj.totalVolume ./ A);
            RT = 0.163 .* obj.totalVolume ./ (A + 4*airAbsorption*obj.totalVolume);
        end
401 402 403 404 405 406 407 408 409 410 411 412
        
        % get surface area of given material
        function S = getSurfaceArea(obj, material)
            
            S = 0; %surface area (scalar)
            for matID = 1:length(obj.bcGroups)
                if (strfind(obj.bcGroups{matID}.name, material))
                        S = S + obj.bcGroups{matID}.surface;                % scalar
                end        
                       
            end
        end
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        
        function materialNames = getMaterialNames(obj)
            
            % check if path model has absolute or relative path (if ':" is
            % in path, path is absolute)
            if ~isempty(strfind(obj.modelFilename, ':'))
                pathToModel = obj.modelFilename;
            else
                pathToModel = fullfile(pwd, obj.modelFilename);
            end
                                
            if exist(pathToModel, 'file') 
                ac3d_file = fopen(pathToModel, 'r');
            else
                error('The specified file does not exist!');
            end
            
            % preallocation
            materialNames = [];
            
            fgetl(ac3d_file); % HEADER ('AC3D' or 'AC3Db' etc.)
            
            count = 1;
            tline = fgetl(ac3d_file);
            while ~isempty(strfind(tline, 'MATERIAL'))
                matNameTmp = textscan(tline, '%s', 'Delimiter', '"');
                materialNames{count} = matNameTmp{1}{2};
                count = count + 1;
                
                tline = fgetl(ac3d_file);
            end
            
            fclose(ac3d_file);
        end
                
        function setMaterialNames(obj, materialNamesCell)
            % check if path model has absolute or relative path (if ':" is
            % in path, path is absolute)
            if ~isempty(strfind(obj.modelFilename, ':'))
                pathToModel = obj.modelFilename;
            else
                pathToModel = fullfile(pwd, obj.modelFilename);
            end
                                
            if exist(pathToModel, 'file') 
                ac3d_file = fopen(pathToModel, 'r');
            else
                error('The specified file does not exist!');
            end
            
            % READ FILE
            matRows = [];
            iRow = 0;
            while ~feof(ac3d_file)
                iRow = iRow + 1;
                tline{iRow} = fgetl(ac3d_file);
                
                if ~isempty(strfind(tline{iRow}, 'MATERIAL'))
                    matRows = [matRows iRow];
                end
            end
            fclose(ac3d_file);
            
            if numel(materialNamesCell) ~= numel(matRows)
                error(['Error! ' num2str(numel(matNames)) ' material names given vs. ' num2str(numel(matRows)) ' material entries in the file.']);
            end
            
            % WRITE FILE WITH CHANGES TO MATERIAL NAMES
            % check if path model has absolute or relative path (if ':" is
            % in path, path is absolute)
            if ~isempty(strfind(obj.modelFilename, ':'))
                pathToModel = obj.modelFilename;
            else
                pathToModel = fullfile(pwd, obj.modelFilename);
            end
                                
            if exist(pathToModel, 'file') 
                ac3d_file = fopen(pathToModel, 'w');
            else
                error('The specified file does not exist!');
            end
            
            count = 0;
            for iRow = 1 : numel(tline)
                if matRows(matRows == iRow)
                    % we are in a material definition row -> update name
                    try
                        lineTmp = textscan(tline{iRow}, '%s', 'Delimiter', '"');
                        count = count + 1;
                        lineTmp{1}{2} = materialNamesCell{count};
                        fprintf(ac3d_file, '%s\r\n', [lineTmp{1}{1} '"' lineTmp{1}{2} '" ' lineTmp{1}{3}]);
                    catch
                        disp(['Error during writing process in AC3D File: ' fullFilename]);
                        fprintf(ac3d_file, '%s\r\n', tline{iRow});
                    end
                else
                    fprintf(ac3d_file, '%s\r\n', tline{iRow});
                end
            end
            fclose(ac3d_file);
        end
        
        function bc_groups = getBcGroups(obj)
            bc_groups = obj.bcGroups;
        end
        
    end % methods
    
end % classdef