%% Teapot Visualization with Shape Copy and Trails
%
% This example reads an STL model of a teapot and displays it in the
% F3D Viewer. Then, further 100 teapots are created with their shapes
% copied from the first object and other properties set randomly.
%
% All these objects are created with the 'Physics' property set to 'true',
% so those that overlap are immediately forced to move away from each
% other. As a result, all teapots move around, bouncing off each other.
%
% Among other properties, the tracing trails are defined for all objects to
% trace their movements. The traces have set random duration (time until
% they decay from the end).

%   Copyright 1998-2021 HUMUSOFT s.r.o.

%% Initialize the 3D Foundation object
FW = F3D.World(mfilename);
initialize(FW, [-20 10 10], [0 0 5]);

% Units and coordinate system
FW.CoordinateSystem = 'unreal';

% Set the viewport properties
VP = FW.Viewports.Main;
VP.Title = mfilename;
Path = fileparts(which(mfilename));
setLogo(VP, fullfile(Path, 'data', 'MatlabLogo.png'));
VP.NavigationSpeed = 10;

% Disable sun shadows for indoor scene
FW.Environment.SunShadows = false;

% Create a scene room from the template
Room = F3D.Geometry.templateRoom(FW.Root, [50 50 20], 0);   % create room and align floor level to 0
Room.Children.Bottom.Color = [0.3 0.2 0.1];
Room.Children.Bottom.TextureMapping.Blend = 1/2;
Room.Children.Bottom.TextureTransform.Scale = 0.1;
Room.Children.Right.TextureMapping.Blend = 1;
displayImage(Room.Children.Right, {'101 Teapots'; 'in a Box'; '^..^'}, 'FontName', 'Courier New');
Room.Children.Left.TextureMapping.Blend = 1/4;
displayImage(Room.Children.Left, 'Left');
Room.Children.Front.TextureMapping.Blend = 1/4;
displayImage(Room.Children.Front, 'Front');
Room.Children.Back.TextureMapping.Blend = 1/4;
displayImage(Room.Children.Back, 'Back');

% Create the instance of a scene root child object and update its shape
% property by importing it from the STL model
MainTeapot = addChild(FW.Root, 'MainTeapot');
load(MainTeapot, fullfile(fileparts(which(mfilename)), 'data', 'teapot.stl'));
MainTeapot.Location = [0 0 10];
MainTeapot.Color = [1 1 1];
MainTeapot.TwoSided = true;
MainTeapot.Gravity = false;
MainTeapot.Physics = true;

% Create 100 new instances, taking their shape from the 'MainTeapot'.
% For each teapot, define also tracing trail with random duration.
for i = 1:100
    newTeapot = addChild(FW.Root, ['TeapotClone' num2str(i)]);
    copy(newTeapot, MainTeapot);
    newTeapot.Color = rand(1, 3)/2;
    newTeapot.Rotation = rand(1, 3)*pi*2;
    newTeapot.Location = rand(1, 3).*[6 6 6] + [-3 -3 7];
    newTeapot.Gravity = false;
    newTeapot.Physics = true;
    newTeapot.Trail = F3D.Type.Trail('Color', newTeapot.Color*2, 'Duration', rand*20);
end
