function result = glassEncodingDemo(showFigure)
% Decode Shatterglass's game data and reconstruct its eight glass volumes.
% Set showFigure to false to return the decoded data without opening a figure.
% The result includes the restored arrays, encoded text, meshes and palette.
% The adaptive range-coding frequency table occupies approximately 256 MiB.

arguments
    showFigure (1,1) logical = true
end

% Decode the stored bytes and restore the array dimensions
packed = glassDataLiteral();
byteCount = 3413;
bytes = decodeAssetBytes(packed,byteCount);
json = native2unicode(bytes,'UTF-8');
constants = restoreGlassArrays(jsondecode(json));

% Verify exact reconstruction of the JSON data and packed text
prepared = prepareGlassArrays(constants);
assert(isequal(jsonencode(prepared,ConvertInfAndNaN = false),json));
assert(isequal(encodeAssetBytes(bytes),packed));

% Reconstruct the vertices, triangular faces and outline edges
models = cell(1,8);
for k = 1:8
    packedCoordinates = constants{148+k}{1};
    packedEdges = constants{148+k}{2};
    vertices = reshape(double(packedCoordinates)-20000,3,[])'/1000;
    faces = convhull(vertices);
    edgeIndices = double(packedEdges)-20000;
    outlineVertices = [vertices;NaN(1,3)];
    edges = outlineVertices(edgeIndices,:);
    models{k} = struct('vertices',vertices,'faces',faces,'edges',edges);
end
palette = reshape(double(constants{141}),3,[])'/1e4-2;
fractureWeights = reshape(double(constants{142})-20000,3,[])'/100;
result = struct('constants',{constants},'json',json,'bytes',bytes, ...
    'packed',packed,'models',{models},'palette',palette, ...
    'fractureWeights',fractureWeights);
if showFigure
    drawVolumes(models,palette);
end
if nargout == 0
    fprintf('%d JSON bytes; %d packed words; eight reconstructed volumes.\n', ...
        numel(bytes),numel(packed)/2);
end
end

function drawVolumes(models,palette)
% Display the eight glass volumes using the game's palette

background = [.027 .043 .058];
fig = figure(Name = 'Glass volumes',NumberTitle = 'off',Color = background, ...
    Position = [80 80 1200 612],DefaultTextInterpreter = 'none');
verticalScale = 680/612;
names = ["Cube","Rectangular prism","Rhombus prism","Hexagonal prism", ...
    "Triangular prism","Square pyramid","Tetrahedron","Octahedron"];
tiers = [1 2 3 4 1 2 3 4];
for k = 1:8
    left = .02+.245*mod(k-1,4);
    bottom = (.53-.47*floor((k-1)/4))*verticalScale;
    ax = axes(fig,Position = [left bottom .225 .37*verticalScale],Color = background);
    hold(ax,'on');
    set(ax,DataAspectRatio = [1 1 1],XLim = [-2.1 2.1],YLim = [-1.65 1.65], ...
        ZLim = [-1.65 1.65],Projection = 'orthographic',SortMethod = 'depth',Visible = 'off');
    view(ax,-30,20);
    camup(ax,[0 0 1]);
    camzoom(ax,1.28);
    drawGlass(ax,models{k},palette,tiers(k));
    annotation(fig,'textbox',[left bottom-.04*verticalScale .225 .04*verticalScale],String = names(k), ...
        Color = [.88 .95 .99],FontName = 'Segoe UI',FontSize = 13,Interpreter = 'none', ...
        HorizontalAlignment = 'center',VerticalAlignment = 'middle',EdgeColor = 'none',Margin = 0);
end
end

function drawGlass(ax,model,palette,tier)
% Shade the triangular faces and draw the outline edges

vertices = model.vertices(model.faces',:);
edges = model.edges;
center = (min(vertices(:,3))+max(vertices(:,3)))/2;
vertices(:,3) = vertices(:,3)-center;
edges(:,3) = edges(:,3)-center;
normals = cross(vertices(2:3:end,:)-vertices(1:3:end,:), ...
    vertices(3:3:end,:)-vertices(1:3:end,:));
normals = normals./vecnorm(normals,2,2);
highlight = .7*exp(-((abs(normals(:,1))-.3)/.13).^2);
faceColors = min(1,.8*(palette(tier,:)+highlight));
alpha = .3+.2*highlight;
patch(ax,Vertices = vertices,Faces = reshape(1:size(vertices,1),3,[])', ...
    FaceVertexCData = repelem(faceColors,3,1),FaceColor = 'interp', ...
    FaceVertexAlphaData = repelem(alpha,3,1),FaceAlpha = 'interp', ...
    AlphaDataMapping = 'none',EdgeColor = 'none');
line(ax,edges(:,1),edges(:,2),edges(:,3),Color = palette(tier+4,:),LineWidth = 1.3);
end

function packed = glassDataLiteral()
packed = '񫋥򛱗񵚄󛳠𨅢󛚳񪨏񜌑𩚮򟱕󬱾𨄉򭜴󓷾񫹎𖟙񘜣񂛸𧈸󀐂񫰄𺘨󨺢󷷴񬊷𲻟𯽾񝡪򅿫򋒺򈚸񟃖򑙺𚖤񤿠􋺶󎻋󨩮򢸽򧧲󸁚𦈂򿷖􌬻𫹅󳨲𨩐񸡔򼢤񛵦񈁀𭂶򐬍񚵪𙿭󱨖򧎋𿆆𠪴򽟃򣔠𙥹󁽀򪎥񩰍񸱁󶔤󊣚򭜆􂮱򖈬񙿼𗼫򎬯񂍄񈊹񶈝򼠅􇆕񒑻񩢺񢠟󯲅񺋆󞺏򾩝򓾴򅠦󴝼񇊔󢂃򦂷񽸴󳞂񞫅򞖻񊌼񊺴󗫭󂫰񨁯𮛂󺦾񐟄񒚼񖶬񀈖򨮷󵊍󛛚񇚲򐾒򂸺􇂸񢐐񡗴󧁀􉟖󚂸򯞈󤾘󍐹𐠹񧴏𧌡󝲰𾄈򝕊򀡴󙈣􎩄󿰀󇝦񆒻񔙁󃛠󎷙󹖧󃒁󽱾󴣬񨤋񞣸񑭧񱅯񅤙񇽶𺭕񪘇񢄫򂾼𣝤𒼃𢻰񟂡󼽀𧯀󎔙𑧼񾽒򞪭񵪜𾰽󇷽񔃗󇢪󠂍񕌓񙳅􊈔򘛸󶎖𶗺󲜀񖯣𞳘򕄌󥓑􆑠𛃦􇌹򺺯񿛂󺒂񞐲򇇋𿇀򭅇񨍟񲵀񤹘򕐝񰠀򬴇𞝰𗸔񭽝𭏫󀆰򯙣񒯒񻳡󝍲􊅴𫏗𖽹󣿡󗁗󁶸󇄩򗓝􉇖򡮽򅧞𫥳󼷷񜓮𮲈񟐧򔱎򕼂񅂢򦎀󊉥𬄥񶡜񓌐󏢇󲦸񋼸򪾈򠱯񜟵󻒣󃰥򻘕𒻰򣻳󼛹񅃋􆣳񙕄񕉰𑑾󠛾񴉣򙃅𨅴񗸡𴷈󏛸񻯹񲪩񀕨󐿐󄟕𡲐󏖔򗐺򸋯𯌼򁜲󧦊򹪫񳞾񣡴񸝜𞝍󔮍􃛇򕀥񱒯󋳚򯾟򵴴󔬬񺌣𽳜񐎯򉑕񥔢񏭖񷐊򘔐𷘮񰖋󆯬󀿐𪰆􍡓𔰎𹃕򒒩򳃯𩜧􎧤𩆃񢽨򗇞񨢤󥟶񵪊󳩽𬋀𛳳󸳲񀸻񨝄𶖔𙲭󂪔𗲀󓺽𡂘𓝄󢸒󽈂󦉁񸊹񩫯򒤧𑯾򓯊󡀞𞛕񇊈񄯮򡯳򩜰򐸪𴿚񿚲򴫇򶵅񆍶򓯖􂁀򵉢𷣗🿡򦙯󓸸􊳃𵲱󙥵𠥣񭈃󟉁򾴛𢏏򙺎󛥱񋃍񇛂񨁍񎆉𴁄󋇃򇚘򜽌󀏖򊉳򂅒􃨅򳄧𧶙򖄯򩚟򆟚񀇛񗐞񊙟󭯖󳇺򥷝񯰢𢜓򄋔󐰇򌟺󢒫򴶎𶯕􊀾󿊂򱓒񋻣𒹘񓨨񼵍񗪰򴢕􂦑񺳫񕕮򿰾󴛾񫲚󊸒򨛚󔜚񳨭򇳀󯷿񤴋򆦐񋯵􌐣񅕍󋏰򒥘𵐴񯳂񗠋򽫌򉇼𰑏𖲂􍿤񾭤󳟜򕀷񑖡򎝳򙳂𩧥𿒇򗷴󶿞𽓘񥵃򦲾󄐇􊞽󲍢򚬎򌒢񓈂񉙛򆐻􄿌򑝎񮓝򮏹񞕔񷆈󋻼󑦾󼜛󌣷𨅐𲜟򸿮󔋍𯹏񸓈𿓖򸿱𰴍򣮌򎟇򮰁񌌨񓒅󈭤򑨥𹇈𕞤񬵢񡥞󂍶􈸃𫎹񆩘򓡱򣧪񥆧󜧡󂑴򕘭󢞑􁻟񌹪󲶍𦸁𬛹򞸫󫎗𓯛򭟅񇏦񤑛򎸻񍕎𿤎򡷔򌄳񠟑򼾕􁙵򛎄򈀓򙉘򽲐󨞾񍟬򛜂񸘹𢉞񆆏𮺊򌇳󤘦򵼲󠠇𙬮򃨘񓓗󯤥򝎉񇩵񔚐𞮚𙕋󺍃𹶢񙭭򇏺򢕵򿒁񹛟񺦾𫪚󥶿񉽚󄤽󂳏𿃡𸜝񊭄𡾻􇼘񇲒󵧈󐕻󨎠𧖼󌶦񸧆𕱗񴥂򋰖򎵎񝬃􄶢񐣍󱬉񛅆򧗂򙷫򑐬񮲑񁺒󶋂򡥱򞯟񊀰񷲥󓪅񏒀􊁥򴅵󴚌򍀰񂈂񦖖󇋂򕨿􎀛񽨹󖼪񛃲򋻜󌳮𳱃񷋖򏀧󘧍󏝈𸽷񆕩񟾷󖀇򇾦񌤒𧍂򈐇󓑧􂴲󕽝򍷈񣈰󽛀󼸧󖣻򞮓𘳭񖝿𤕪񱊜񁭲􀨐򝍲󒝓𵄸𙾤򿝪󖵸󭶱󖲡񼅶񳩋𫭿񇜇󅞘򚆢󞿣𽓒񹽷򅂿򽗤􎈱𢇃';
end

function packed = encodeAssetBytes(bytes)
% Compress the bytes using adaptive range coding

arguments
    bytes (1,:) uint8
end

words = assetRangeCodec("encode",double(bytes)+1);
% Pack each 20-bit word into a UTF-16 surrogate pair
high = 55296+floor(words/1024);
low = 56320+mod(words,1024);
packed = char(reshape([high;low],1,[]));
assert(isequal(native2unicode(unicode2native(packed,'UTF-8'),'UTF-8'),packed));
end

function bytes = decodeAssetBytes(packed,count)
% Recover the bytes from the encoded character vector

arguments
    packed (1,:) char
    count (1,1) double {mustBeInteger,mustBeNonnegative}
end

units = double(packed);
assert(mod(numel(units),2) == 0);
assert(all(units(1:2:end) >= 55296 & units(1:2:end) <= 56319));
assert(all(units(2:2:end) >= 56320 & units(2:2:end) <= 57343));
words = [1024 1]*reshape(mod(units,1024),2,[]);
bytes = uint8(assetRangeCodec("decode",words,count)-1);
end

function result = assetRangeCodec(action,values,count)
% Encode or decode symbols using adaptive range coding
% Encoding takes symbols 1:256; decoding takes 20-bit words and the symbol count

arguments
    action (1,1) string {mustBeMember(action,["encode","decode"])}
    values (1,:) double {mustBeInteger,mustBeNonnegative}
    count (1,1) double {mustBeInteger,mustBeNonnegative} = numel(values)
end

alphabet = 256;
order = 4;
hashSize = 131071;
escape = 16;
radix = 2^20;
threshold = 8e9;
assert(radix*threshold < flintmax);
frequencies = zeros(alphabet,hashSize);
interval = 1;
position = 1;
offset = 0;
encoding = action == "encode";
assert(encoding || nargin >= 3,'Decoding requires the original symbol count.');
if encoding
    assert(all(values >= 1 & values <= alphabet));
    assert(count == numel(values));
    symbols = [zeros(1,order),values];
    words = [];
else
    assert(all(values < radix));
    symbols = zeros(1,count+order);
    words = values;
end

for index = order+1:count+order
    % Expand the interval using 20-bit words
    while interval < threshold
        interval = interval*radix;
        if encoding
            words(end+1) = 0; %#ok<AGROW>
        else
            assert(position <= numel(words),'Compressed stream ended early.');
            offset = offset*radix+words(position);
            position = position+1;
        end
    end

    % Combine frequencies from contexts of up to four preceding symbols
    context = [0,cumsum(symbols(index-(1:order)).*alphabet.^(0:order-1))];
    columns = mod(context*31+(0:order)*7777,hashSize)+1;
    counts = frequencies(:,columns);
    weights = cumprod(escape./(escape+sum(counts)),'reverse');
    boundaries = [0;cumsum(1+floor((counts*(weights'/escape)+weights(1)/alphabet)*radix))];
    unit = floor(interval/boundaries(end));
    assert(unit > 0);

    if encoding
        symbol = symbols(index);
        carry = boundaries(symbol)*unit;
        % Propagate the interval offset through the output words
        for digit = numel(words):-1:1
            total = words(digit)+mod(carry,radix);
            words(digit) = mod(total,radix);
            carry = floor(carry/radix)+floor(total/radix);
            if carry == 0
                break
            end
        end
        assert(carry == 0);
    else
        symbol = find(boundaries > offset/unit,1)-1;
        assert(~isempty(symbol) && symbol >= 1 && symbol <= alphabet);
        offset = offset-boundaries(symbol)*unit;
        symbols(index) = symbol;
    end
    interval = (boundaries(symbol+1)-boundaries(symbol))*unit;
    frequencies(symbol,columns) = frequencies(symbol,columns)+1;
end
if encoding
    result = words;
else
    result = symbols(order+1:end);
end
end

function value = prepareGlassArrays(value)
% Preserve dimensions for complex, multidimensional and empty numeric arrays

if iscell(value)
    value = cellfun(@prepareGlassArrays,value,UniformOutput = false);
elseif isnumeric(value) && (~isreal(value) || ~ismatrix(value) ...
        || (isempty(value) && ~isequal(size(value),[0 0])))
    value = struct('r',real(value(:))','i',imag(value(:))','s',size(value));
end
end

function value = restoreGlassArrays(value)
% Restore the recorded array dimensions and complex values
% r and i store the flattened components; s stores the original dimensions

if isstruct(value) && numel(value) > 1
    value = num2cell(value);
end
if isstruct(value)
    assert(all(isfield(value,{'r','i','s'})));
    value = reshape(value.r+1i*value.i,value.s');
    return
end
if iscell(value)
    value = cellfun(@restoreGlassArrays,value,UniformOutput = false);
end
if iscolumn(value)
    value = value';
end
end
